开发者

Parse XML with repeated pattern of nodes

Can you please give me some ideas on the best way to parse an XML document in C#?

<RESPONSE>
  <FNAME>user1</FNAME>
  <LNAME>lastname1</LNAME>
  <ADDRESS>
     <LINE1>line 1 for user 1</LINE1>
     <LINE2>line 2 for user 1</LINE2>
     .....
     .....
  </ADDRESS>
  <开发者_JAVA百科FNAME>user2</FNAME>
  <LNAME>lastname2</LNAME>
  <ADDRESS>
     <LINE1>line 1 for user 2</LINE1>
     <LINE2>line 2 for user 2</LINE2>
     .....
     .....
  </ADDRESS>

</RESPONSE>

This is data returned from an online XML service and it is obviously not really well formed, as the nesting is not applied properly for each of the different elements. Is there a way I can avoid a line by line parsing and text comparison?


Here you go:

XmlTextReader xml = new XmlTextReader("response.xml");
while (xml.Read())
{
    switch (xml.NodeType)
    {
        case XmlNodeType.Element:
            {
                if (xml.Name == "RESPONSE") Console.WriteLine("Response: ");
                if (xml.Name == "FNAME")
                {
                    Console.Write("First Name: ");
                }
                if (xml.Name == "LNAME")
                {
                    Console.Write("Last Name: ");
                }
                if (xml.Name == "ADDRESS") Console.WriteLine("Address: ");
                if (xml.Name == "LINE1")
                {
                    Console.Write("Line 1: ");
                }
                if (xml.Name == "LINE2")
                {
                    Console.Write("Line 2: ");
                }
            }
            break;
        case XmlNodeType.Text:
            {
                Console.WriteLine(xml.Value);
            }
            break;
        default: break;
    }
}
Console.ReadKey();


Linq to Xml is the the modern way of parsing XML using .NET

the following snippet will give you access to all of the FNAME elements

var doc = XDocument.Parse(xml);
foreach (var fname in doc.Root.Elements("FNAME") {
  // fname.Value has the element value
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜