【问题标题】:How to get the attribute value of an xml code using linq如何使用linq获取xml代码的属性值
【发布时间】:2014-01-28 17:16:02
【问题描述】:
<Shape ID="1" NameU="Start/End" Name="Start/End" Type="Shape" Master="2">
 ....</Shape>
<Shape ID="2" NameU="Start/End" Name="Start/End" Type="Shape" Master="5">
 ....</Shape>

我必须为每个 ID 值返回主值。 我如何通过使用 LINQ to XMl 来实现它。

【问题讨论】:

    标签: c#-4.0 xml-parsing linq-to-xml


    【解决方案1】:

    您并没有真正展示您的 XML 文档的外观,所以我假设它如下所示:

    <Shapes>
      <Shape ID="1" NameU="Start/End" Name="Start/End" Type="Shape" Master="2">
      </Shape>
      <Shape ID="2" NameU="Start/End" Name="Start/End" Type="Shape" Master="5">
      </Shape>
    </Shapes>
    

    您可以像这样简单地获取所有不同IDMaster 属性值:

    var xDoc = XDocument.Load("Input.xml");
    
    var masters = xDoc.Root
                      .Elements("Shape")
                      .ToDictionary(
                        x => (int)x.Attribute("ID"),
                        x => (int)x.Attribute("Master")
                      );
    

    masters 将是Dictionary&lt;int, int&gt;,其中键是您的ID,值是对应的Master 属性值。

    【讨论】:

      猜你喜欢
      • 2013-02-22
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多