This is my code:
var objectText = XmlReader.Create(requestedURL);
XmlSerializer mySerializer = new XmlSerializer(typeof(InstagramItems));
var instagramItems = (InstagramItems)mySerializer.Deserialize(objectText);
but seems it can't work with RSS (which are "XML more or less"):
Server Error - <rss xmlns=''> was not expected.
How can I do it? I believe there are .NET library without using 3rd part plugins.
Part of the RSS:
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
<channel>
<title>Photos tagged as "example" on Instagram</title>
<link>http://instagram.com</link>
<description>Photos tagged as "example" on Instagram</description>
<atom:link href="http://instagram.com/tags/example/feed/recent.rss" rel="self" />
</channel>
Step 1: Download the RSS XSD : http://www.thearchitect.co.uk/schemas/rss-2_0.xsd
Step 2: Use xsd.exe to generate an RSS type based on the schema
Step 3: If objectText is only an RSS document, then just substitute your newly created RSS type for InstagramITems in the above code.
Step 3a: If the object text is mixed Instagram and RSS code, then use the DataContractSerializer and pre-register both Instagram and RSS types with the DataContractSerializer before attempting to deserialize
XmlSerializer works with specific xml format, if you suply any other format other then which it expects the metioned exception will be throwned.
You can parse the xml manualy and create InstagramItems from the parsed xml, I would recommed using linq to xml here is an example http://social.msdn.microsoft.com/Forums/vstudio/en-US/e38e69ac-d325-4cc4-bdf7-bc940e19e63f/read-xml-and-create-objects-using-linq
Related
I'm creating an XML file programatically. To create the starting tag I have the code:
Dim XDoc As XDocument = <?xml version="1.0" encoding="UTF-8" standalone="yes"?><Customers></Customers>
It's then followed by looping through the data, adding in the required elements using the Root.Add method. The XML displays in the browser successfully.
Xdoc.Root.Add(<customer>
<fields>
</customer>
When some clients connect to this XML data, if there is no data to retrieve the page is displayed as:
<?xml version="1.0"?>
<Customers/>
When reading the XML URL from a .NET project:
Dim Xdoc As XDocument = XDocument.Load(UrlToXmlFile)
The error "DTD must be defined before the document root element" is thrown.
Although I can trap the error, I thought perhaps I may have done something wrong when creating the XML (XML isn't my strong point).
Some sites suggest adding a DTD (<!DOCTYPE note SYSTEM "Note.dtd"> for example). I don't know if this is correct or if I can ignore the error or if there is a better way to to declare this?
Update: when i view the page directly in Chrome, it displays the XML as
<Customers>
<customer>....</customer>
<customer>....</customer>
</Customers>
in IE it displays as
<?xml version="1.0"?>
<Customers>
<customer>....</customer>
<customer>....</customer>
</Customers>
but in both browsers when i look at 'view source' it shows
<Customers>
<customer>....</customer>
<customer>....</customer>
</Customers>
I don't know of this would be an issue?
Update 2
XDoc.Save(Sr)
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/xml"
Response.Write(Sr.GetStringBuilder.ToString)
Response.Flush()
Response.End()
Here is an example showing the generation/saving and loading of your xml with no errors.
Dim XmlFile As String = "C:\\Temp\\TestData.xml"
Dim XDoc As XDocument = <?xml version="1.0" encoding="UTF-8"?><Customers></Customers>
For ForCount As Integer = 0 To 10
XDoc.Root.Add("<customer>Customer" & ForCount.ToString & "</customer>")
Next
XDoc.Save(XmlFile)
Dim XDocReader As XDocument = XDocument.Load(XmlFile)
Also it sounds like you might be using a web service. Use fiddler to verify your web service is not adding in that attribute when serving the data. I do not see how you are exporting the XML. Make sure you are not just doing a .ToSrting on XDoc, that will only generate the inner XML.
How can I display XML output on ASP.NET page with XML tags?
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonOutput, "root");
Console.WriteLine(doc.OuterXml);
I would like to get results on my page like this:
<root>
<id>108013515952807</id>
<posts>
<data>
<message>This...Game... http://www.youtube.com/watch?v=l8Xsex0pqXY</message>
<id>108013515952807_470604423027046</id>
<created_time>2013-05-15T20:02:31+0000</created_time>
</data>
<data>
<message>Streaming in a few minutes! http://www.youtube.com/watch?v=IYnHDT6V82k</message>
<id>108013515952807_470538076367014</id>
<created_time>2013-05-15T16:46:36+0000</created_time>
</data>
</posts>
</root>
I tried this but I get no XML tags like in example above.
Response.Write("<BR>" + doc.OuterXml);
If you just put XML onto a webpage, the browser thinks it might be HTML and "renders" it, which is why you can't see the tags. You need to encode the XML
You can use the method
Response.Write(Server.HtmlEncode(doc.OuterXml));
Try
XElement.Parse(request.OuterXml).ToString()
If you want prettified XML string,
refer to: What is the simplest way to get indented XML with line breaks from XmlDocument?
when I am running this program, I am facing this error
public static object Load(Stream stream,Type newType)
{
//create s serializer and load the object
XmlSerializer serializer=new XmlSerializer(newType);
object newobject =serializer.Deserialize(stream);
//return the new object
return newobject;
}
?xml version="1.0"?>
-<Address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <FirstName>ali </FirstName> <FamilyName>bradaran</FamilyName> <UserLevel>عادی</UserLevel> <Password>123</Password> </Address>
Your problem is that there is an error in the XML document you are trying to read.
Open your XML document in Internet Explorer. If it is valid, it will display. If it is not, the error will be described and shown, which should help you track down the problem.
If the XML you posted is a genuine representation of what you're reading, there is a minus character and two semicolon characters that shouldn't be in the file. I'm also not sure you would want the xmlns attributes in your Address element?
I suggest you search for some XML tutorials on the web so you can get a better understanding of how XML must be formed.
I want to read all XML contents from a file. The code below only works when the XML declaration (<?xml version="1.0" encoding="UTF-8"?>) is removed. What is the best way to read the file without removing the XML declaration?
XmlTextReader reader = new XmlTextReader(#"c:\my path\a.xml");
reader.Read();
string rs = reader.ReadOuterXml();
Without removing the XML declaration, reader.ReadOuterXml() returns an empty string.
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://www.as.com/ver/ver.IClaimver/Car</a:Action>
<a:MessageID>urn:uuid:b22149b6-2e70-46aa-8b01-c2841c70c1c7</a:MessageID>
<ActivityId CorrelationId="16b385f3-34bd-45ff-ad13-8652baeaeb8a" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">04eb5b59-cd42-47c6-a946-d840a6cde42b</ActivityId>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">http://localhost/ver.Web/ver2011.svc</a:To>
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Car xmlns="http://www.as.com/ver">
<carApplication>
<HB_Base xsi:type="HB" xmlns="urn:core">
<Header>
<Advisor>
<AdvisorLocalAuthorityCode>11</AdvisorLocalAuthorityCode>
<AdvisorType>1</AdvisorType>
</Advisor>
</Header>
<General>
<ApplyForHB>yes</ApplyForHB>
<ApplyForCTB>yes</ApplyForCTB>
<ApplyForFSL>yes</ApplyForFSL>
<ConsentSupplied>no</ConsentSupplied>
<SupportingDocumentsSupplied>no</SupportingDocumentsSupplied>
</General>
</HB_Base>
</carApplication>
</Car>
</s:Body>
</s:Envelope>
Update
I know other methods that use NON-xml reader (e.g. by using File.ReadAllText()). But I need to know a way that uses an xml method.
There can be no text or whitespace before the <?xml ?> encoding declaration other than a BOM, and no text between the declaration and the root element other than line break.
Anything else is an invalid document.
UPDATE:
I think your expectation of XmlTextReader.read() is incorrect.
Each call to XmlTextReader.Read() steps through the next "token" in the XML document, one token at a time. "Token" means XML elements, whitespace, text, and XML encoding declaration.
Your call to reader.ReadOuterXML() is returning an empty string because the first token in your XML file is an XML declaration, and an XML declaration does not have an OuterXML.
Consider this code:
XmlTextReader reader = new XmlTextReader("test.xml");
reader.Read();
Console.WriteLine(reader.NodeType); // XMLDeclaration
reader.Read();
Console.WriteLine(reader.NodeType); // Whitespace
reader.Read();
Console.WriteLine(reader.NodeType); // Element
string rs = reader.ReadOuterXml();
The code above produces this output:
XmlDeclaration
Whitespace
Element
The first "token" is the XML declaration.
The second "token" encountered is the line break after the XML declaration.
The third "token" encountered is the <s:Envelope> element. From here a call to reader.ReadOuterXML() will return what I think you're expecting to see - the text of <s:Envelope> element, which is the entire soap packet.
If what you really want is to load the XML file into memory as objects, just call
var doc = XDocument.Load("test.xml")
and be done with the parsing in one fell swoop.
Unless you're working with an XML doc that is so monstrously huge that it won't fit in system memory, there's really not a lot of reason to go poking through the XML document one token at a time.
What about
XmlDocument doc=new XmlDocument;
doc.Load(#"c:\my path\a.xml");
//Now we have the XML document - convert it to a String
//There are many ways to do this, one should be:
StringWriter sw=new StringWriter();
doc.Save(sw);
String finalresult=sw.ToString();
EDIT: I'm assuming you mean you actually have text between the document declaration and the root element. If that's not the case, please clarify.
Without removing the extra text, it's simply an invalid XML file. I wouldn't expect it to work. You don't have an XML file - you have something a bit like an XML file, but with extraneous stuff before the root element.
IMHO you can't read this file. It's because there's a plain text before the root element <s:Envelope> which makes whole document invalid.
You're parsing an XML document as XML just to obtain the source text? Why?
If you really want to do that then:
string rs;
using(var rdr = new StreamReader(#"c:\my path\a.xml"))
rs = rdr.ReadToEnd();
Will work, but I'm really not sure that is what you actually want. This pretty much ignores that it's XML and just reads the text. Useful for some things, but not a lot.
I need to generate XML on MonoTouch application ? How i can create like this,
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
...
</root>
I need to post the XML to web service as string format. And again I want to parse the response data. Response data also XML format string. I done it in j2me applications. But I don't know how to do this on MonoTouch? Anyone tell me How to do this?
My favorite API these days is the System.Xml.Linq API, look at the documentation and samples here:
http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx
For what you want, this is very easy:
var s = new XDocument () {
new XElement ("root")
};
Console.WriteLine ("The XML is: {0}", s.ToString ());
You can create the XML by using the XmlWriter class.
The easiest way to parse XML would be to use LINQ.