阅读复杂的XML

时间:2011-12-28 03:44:26

标签: c# xml .net-2.0 linq-to-xml

我很难从那个xml中读取!我认为XMLDocument会有所帮助,但我不知道如何从childNode中的每个元素获取值!

尤其是具有任何childNode Inside的子节点,如IdList。

XML格式:

 <sdnEntry>

<programList>
  <program>SDNT</program>
</programList>

<idList>
  <id>
    <uid>6028</uid>
    <idType>NIT #</idType>
    <idNumber>900106267-0</idNumber>
    <idCountry>Colombia</idCountry>
  </id>
  <id>
    <uid>6029</uid>
    <idType>N0T #</idType>
    <idNumber>900106267-1</idNumber>
    <idCountry>Colombian</idCountry>      
  </id>
</idList>
</sdnEntry>

代码:

XmlDocument doc = new XmlDocument();
doc.Load(@"D:\SDN1.xml");

XmlElement root = doc.DocumentElement;                

XmlNodeList sdnEntryNodeList = root.GetElementsByTagName("sdnEntry"); 

foreach (XmlNode sdnNode in sdnEntryNodeList)
{
    for (int row = 0; row < sdnEntryNodeList.Count; row++)
    {
        XmlNodeList programListNodeList = sdnNode["programList"].GetElementsByTagName("program");

        foreach (XmlNode programNode in programListNodeList)
        {
            program = programNode.InnerText;
        }

        XmlNodeList idListNodeList = element["idList"].GetElementsByTagName("id");

        foreach (....)
        {

        }
     }       

}

以上代码,是不是很好?否则,我会接受你的所有建议,请发表评论......

如何在那个复杂的XML中读取programList和idList?

3 个答案:

答案 0 :(得分:0)

如果您想使用XMLDocument,这里有一个示例

var programList = doc.SelectNodes("/sdnEntry/programList/program");
var idList = doc.SelectNodes("/sdnEntry/idList/id");

答案 1 :(得分:-2)

使用 linq to xml。

http://msdn.microsoft.com/en-us/library/bb397976.aspx

<强>示例:

foreach(var node in doc.Elements("idList").Elements("id").Elements("uid")) 

答案 2 :(得分:-2)

我会使用以下linq-to-xml查询来简化代码。

var programs = from program in 
               doc.Root.Element("programList").Descendants("program")
               select program.Value;

var ids = from id in doc.Root.Element("idList").Descendants("id")
          select new
          {
               uid = (string)id.Element("uid"),
               idType = (string)id.Element("idType"),
               idNumber = (string)id.Element("idNumber"),
               idCountry = (string)id.Element("idCountry")
          };