开发者

how to read XML file using xml reader?

Question 1: Assume that i am reading XmlNodeType.Text and I would like to know its tag node name. How do you do that without moving cursor up or down? Also How can I know parent tag of current node tag?

Question 2: Assume that I am reading xml file and I would like to start at particular node tag. How can do that?

Question 3: if you have xsd file, is there easy way to upload xml file? I am using C# 3.5 .net and sql server 2008.

This is what i wrote so far:

XmlTextReader reader = new XmlTextReader("datafile.xml");
while (reader.Read())
{
    if (reader.NodeType == XmlNodeType.Element)
    {
        Console.Write(reader.Name);
    }
    else if (reader.NodeType == XmlNodeType.Text)
    {
        Console.Write("/"+reader.Name+"/" + reader.Value+"/");
    }
    else
    {
        if (reader.NodeType == XmlN开发者_如何学运维odeType.EndElement)
        {
            Console.WriteLine(reader.Name);
            Console.ReadLine();
        }
    }
}
reader.Close();

Please let me know if you need more clarification


XmlReader is stateless and only retains information about the current node, so if you are reading the content of an element and wish to know the elements name you need to make sure that when you read the start element node you somehow retain the element name.

Again if you want to know the name of the parent element you need to retain this information / state yourself as you read through the xml document.

If you wish to start reading at a particular node you should go through and read the xml document node by node until you read the node you wish to start at.

Ultimately reading xml via the XmlReader class is more difficult than the alternatives, generally speaking you would only use XmlReader if the the xml document is very large, in most other cases using one of the alternatives:

  • Linq to XML
  • The XmlDocument class
  • Using XSD.exe to generate a .Net class from a XSD file that can be used to serialise and deserialise xml via the XmlSerializer class.

For more information see XML Serialization in the .NET Framework

If you really want to use XmlReader then you should read Using the XmlReader Class .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜