【问题标题】:ParseXML how compare one attribute for take the value of the other in the same elementParseXML如何比较一个属性以获取同一元素中另一个属性的值
【发布时间】:2014-12-19 09:41:00
【问题描述】:

我有这个 xml 代码:

<Turn>
    <Entry type="TurnIn" msgId="124312">
        <field tag="35" val="D"/>
        <field tag="34" val="003694"/>
        <field tag="43" val="20140916-01:29:07"/>
    </Entry>
    <Entry type="Van" msgId="234325">
        <field tag="35" val="8"/>
        <field tag="34" val="005046"/>
        <field tag="43" val="20140916-01:31:17"/>
    </Entry>
    <Entry type="fired" msgId="124864">
        <field tag="35" val="8"/>
        <field tag="34" val="005049"/>
        <field tag="43" val="20140916-01:34:49"/>
    </Entry>
    <Entry type="fired" msgId="134864">
        <field tag="35" val="8"/>
        <field tag="34" val="006324"/>
        <field tag="43" val="20140916-01:35:20"/>
    </Entry>
</Turn>    

对于 C#。

我需要在列表中获取 val where Entry, type = "fired" 和 field,tag = 34 和 43。我已经多次尝试使用 XmlReader 类和 Linq to XMl。我不知道如何将同一元素中的一个属性与另一个属性的值进行比较。

【问题讨论】:

  • 您是否还需要在特定日期进行过滤..?或者您是否要返回 type = 已触发且字段标记包含 35 AND 43...的所有节点?听起来你可以使用XPATH
  • 您希望这些值如何?全部捆绑在一个集合中,而不引用父元素或集合中的每个值都引用父元素?
  • 两个答案都是正确的。我不尝试使用 XPath,但我认为这句话应该是正确的谢谢

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


【解决方案1】:

这可以使用 Linq to XML 完成,如下所示

XDocument xDoc = XDocument.Parse(yourXMLString);

//XDocument xDoc = XDocument.Load(yourXMLFilePath);

var res = xDoc.Descendants("Entry")
              .Where(x => x.Attribute("type").Value == "fired")
              .Elements("field")
              .Where(y => y.Attribute("tag").Value == "34" || y.Attribute("tag").Value == "43")
              .Select(a => a.Attribute("val").Value);

【讨论】:

    【解决方案2】:

    使用XPathDocument(参见http://support.microsoft.com/kb/308333)和类似的XPath查询

    //Turn/Entry[@type='fired']/field[@tag=34|@tag=43]@val
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多