如何在每次迭代c#中读取XML子节点元素属性?

时间:2017-10-26 14:52:20

标签: c# xml

<?xml version="1.0" encoding="utf-8" ?>
<Checkplan>
  <masters>   
    <sections>
      <characteristics>
        <characterstic name="xxx1">
        </characterstic>
        <characterstic name="xxx2">
        </characterstic>
        <image id="xxx"></image>
      </characteristics>
    </sections>    
    <sections>
      <characteristics>
        <characterstic name="yyy1">
        </characterstic>
        <characterstic name="yyy2">
        </characterstic>
        <image id="yyy"></image>
      </characteristics>
    </sections>   

  </masters>
</Checkplan>

图片ID xxx对于xxx1和xxx2是常见的。 图像ID yyy对于yyy1和yyy2是常见的,所以我需要在第一次迭代中仅循环通过xxx相关属性然后我有 在下一次迭代中阅读yyy reated。 应该为每个部分运行迭代。

 XmlNodeList dataNodes = xml.SelectNodes("//Section");
                foreach (XmlNode node in dataNodes)
                {

                    foreach (XmlNode childNode in node.ChildNodes)
                    {


                        foreach (XmlNode childNode2 in childNode.ChildNodes)
                        {

                            FeatureName = childNode2.Attributes["Name"].Value;
                            LSL = Convert.ToInt32(childNode2.Attributes["LSL"].Value);
                            USL = Convert.ToInt32(childNode2.Attributes["USL"].Value);

                        }
                    }
                    if (!FeaturesCollection.ContainsKey(FeatureName))
                    {

                        FeaturesCollection.Add(FeatureName, new Features { m_Name = FeatureName, m_LSL = LSL, m_USL = USL, m_ImageID = imageid });
                    }

1 个答案:

答案 0 :(得分:0)

使用xml linq。你留下了一个&#39; i&#39;超出xml文件中的特征。请参阅以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("characteristics").Select(x => new {
                id = (string)x.Element("image").Attribute("id"),
                characteristics = x.Elements("characteristic").ToList().Select(y => (string)y.Attribute("name")).ToList()
            }).ToList();
        }
    }
}