簡體   English   中英

如何在每次迭代 c# 中讀取 XML 子節點元素屬性?

[英]How to read XML child node element attributes in each iteration c#?

<?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 });
                    }

使用 xml linq。 您在 xml 文件中留下了“i”的特征。 見下面的代碼:

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();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM