使用C#在XML文件中选择nodes属性

时间:2014-02-12 10:07:34

标签: c# xml xmlnode

在以下XML文件中,我尝试在列表中保存所有id属性:

<?xml version="1.0"?>
<PressReleases>
  <PressRelease id="545" version="1">
    <Name>Convert number to string</Name>
    <Date>20/05/1985</Date>
    <Input>1</Input>
    <Output>One</Output>
  </PressRelease>
  <PressRelease id="544" version="1">
    <Name>Find succeeding characters</Name>
    <Date>19/05/1985</Date>
    <Input>abc</Input>
    <Output>def</Output>
  </PressRelease>
  <PressRelease id="543" version="1">
    <Name>Convert multiple numbers to strings</Name>
    <Date>17/05/1985</Date>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </PressRelease>
  <PressRelease id="542" version="1">
    <Name>Find correlated key</Name>
    <Date>02/05/1985</Date>
    <Input>a1</Input>
    <Output>b1</Output>
  </PressRelease>
  <PressRelease id="541" version="1">
    <Name>Count characters</Name>
    <Date>04/02/1985</Date>
    <Input>This is a test</Input>
    <Output>14</Output>
  </PressRelease>
  <PressRelease id="540" version="1">
    <Name>Another Test</Name>
    <Date>09/01/1985</Date>
    <Input>Test Input</Input>
    <Output>10</Output>
  </PressRelease>
</PressReleases>

此代码块仅保存在第一个新闻发布节点(545)中写入的第一个Id。 我需要所有这些(545,544等)

    XmlDocument doc = new XmlDocument();
    doc.Load(@"C:\Users\ARNAUDR\Desktop\test.xml");
    //string xmlcontents = doc.InnerXml;

    XmlNodeList xnList = doc.SelectNodes("/PressReleases");
    List<int> IDsInDistantXML = new List<int>();
    foreach (XmlNode xn in xnList)
    {
        XmlNode PressRelease = xn.SelectSingleNode("PressRelease");
        if (PressRelease != null)
        {
            IDsInDistantXML.Add(Convert.ToInt16(PressRelease.Attributes["id"].Value));
        }
    }

提前感谢您的帮助

2 个答案:

答案 0 :(得分:2)

我建议您使用Linq to Xml:

XDocument xdoc = XDocument.Load(@"C:\Users\ARNAUDR\Desktop\test.xml");
List<int> ids = xdoc.Root.Elements("PressRelease")
                    .Select(pr => (int)pr.Attribute("id"))
                    .ToList();

注意:您的问题是您始终从root选择第一个(单个节点)PressRelease节点,并且您枚举根节点(始终为1)而不是枚举PressRelease节点。这是固定的解决方案:

XmlNodeList pressReleases = doc.SelectNodes("/PressReleases/PressRelease");
List<int> IDsInDistantXML = new List<int>();
foreach (XmlNode pr in pressReleases)    
    IDsInDistantXML.Add(Convert.ToInt32(pr.Attributes["id"].Value));    

答案 1 :(得分:1)

或者,如果您只需要一个属性,请将SelectNodes xpath直接更改为节点:

List<int> IDsInDistantXML = new List<int>();
foreach (var xn in doc.SelectNodes("/PressReleases/PressRelease"))
{
    IDsInDistantXML.Add(Convert.ToInt16(xn.Attributes["id"].Value));
}