简体   繁体   English

使用重复的节点模式解析XML

[英]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#? 您能否给我一些有关在C#中解析XML文档的最佳方法的想法?

<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. 这是从在线XML服务返回的数据,由于嵌套不适用于每个不同的元素,因此显然格式不是很正确。 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 Linq to Xml是使用.NET解析XML的现代方法

the following snippet will give you access to all of the FNAME elements 以下代码段将使您可以访问所有FNAME元素

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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