I want to read xml file in asp.net use c# and also to write I tried this code
using (XmlReader reader = XmlReader.Create(Server.MapPath("TestXml.xml")))
{
reader.Read();
while (reader.Read())
{
Response.Write( reader.Value.ToString());
Response.Write("<br />");
}
}
and the output is:

and the xml is
<?xml version="1.0" encoding="utf-8" ?>
<note>
<to>Chayem</to>
<from>Shaul</from>
<heading>Way?</heading>
<body>because</body>
</note>
What do I do? Thank you.
XmlReader.Read()always processes the next node in the document. Note: node, not element. If you step through that code and examine each node, you’ll see that while there are only six elements in the XML document, theXmlReaderis processing eleven nodes.This is because your XML document (like most) has text nodes containing whitespace characters between the elements. Your code is writing a
<br/> to the response every time theXmlReaderencounters a node. What you want is to write one out every time theXmlReaderencounters an element with text content.A way to do this is to simply only write out nodes that contain something other than whitespace, e.g.:
But why are you even using an
XmlReader? There are much easier ways to generate this output. Load the XML into anXDocument, for instance, and you can produce the output like this: