简体   繁体   中英

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>
  <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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM