如何处理.net中具有相同节点的xml文件

时间:2016-11-21 01:30:53

标签: c# .net xml

我有一个xml文件,我发布的部分如下所示

<?xml version="1.0" encoding="utf-8"?>
<bulkCmConfigDataFile>
  <fileHeader/>
  <configData>
    <class name="FPE">
      <object technique="FPE" vendor="test" version="123">
        <class name="eNodeBCell_eNodeB">
          <object>
            <parameter name="LocalCellId" value="0"/>
          </object>
        </class>
        <class name="eNodeB_eNodeB">
          <object>
            <parameter name="eNodeBId" value="64946"/>
          </object>
        </class>
      </object>
    </class>
  </configData>
</bulkCmConfigDataFile>

我在c#中有两个string变量,如localCellIdenodebId,所以我希望localCellId值为0,enodebId值为64946.How在c#中获取它 我试过这种方式,但没有结果

    XElement main = XElement.Load(path);

    var results = main.Descendants("eNodeBCell_eNodeB")
        .Descendants("parameter")
        .Where(e => e.Value == "LocalCellId")
        .Select(e => new { localcellid = e.Descendants("LocalCellId").FirstOrDefault().Value});

2 个答案:

答案 0 :(得分:2)

如果您只想要这两个元素的value属性,那么您可以使用XPath表达式。

var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<bulkCmConfigDataFile>
  <fileHeader/>
  <configData>
    <class name=""FPE"">
      <object technique=""FPE"" vendor=""test"" version=""123"">
        <class name=""eNodeBCell_eNodeB"">
          <object>
            <parameter name=""LocalCellId"" value=""0""/>
          </object>
        </class>
        <class name=""eNodeB_eNodeB"">
          <object>
            <parameter name=""eNodeBId"" value=""64946""/>
          </object>
        </class>
      </object>
    </class>
  </configData>
</bulkCmConfigDataFile>";

var document = XDocument.Parse(xml);

var localCellId = document.XPathSelectElement("//parameter[@name='LocalCellId']").Attribute("value").Value as string;
var eNodeBId = document.XPathSelectElement("//parameter[@name='eNodeBId']").Attribute("value").Value as string;

Console.WriteLine("LocalCellId: {0}", localCellId);
Console.WriteLine("eNodeBId: {0}", eNodeBId);

答案 1 :(得分:1)

基于您的LINQ to XML尝试,我认为您正在寻找的XPath是这样的:

var xDoc = new System.Xml.XmlDocument();
xDoc.Load("1.xml");
string localcellid = xDoc.SelectSingleNode("//*[@*='eNodeBCell_eNodeB']//parameter[@*='LocalCellId']/@value").Value;
string eNodeBId = xDoc.SelectSingleNode("//*[@*='eNodeB_eNodeB']//parameter[@*='eNodeBId']/@value").Value;

您可以将[@*='替换为[@name='(我测试了两者)并向XPath添加更多特定信息。

为了比较,LINQ to XML版本:

var main = System.Xml.Linq.XDocument.Load("1.xml");

string localcellid = main.Descendants()
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeBCell_eNodeB"))
    .Descendants("parameter")
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "LocalCellId"))
    .Attribute("value").Value;

string eNodeBId = main.Descendants()
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeB_eNodeB"))
    .Descendants("parameter")
    .FirstOrDefault(x => x.Attributes().Any(a => a.Value == "eNodeBId"))
    .Attribute("value").Value;