简体   繁体   English

使用LINQ to XML解析XML

[英]parse XML using LINQ to XML

I have the following XML node: 我有以下XML节点:

<reportDataRow>
    <columnData colNum="1">
        <data>FirstName</data>
    </columnData>
    <columnData colNum="2">
        <data>LastName</data>
    </columnData>
</reportDataRow>

I want to retrieve the value from the data node based on the value of the colNum attribute in the columnData node. 我想基于columnData节点中colNum属性的值从data节点中检索值。

How would I accomplish that using LINQ? 我将如何使用LINQ做到这一点?

again assuming reportDataRow is an XElement and value is a variable that you want to match the colNum attribute with; 再次假设reportDataRow是XElement,value是要与colNum属性匹配的变量;

foreach (var selected in reportDataRow.Elements("columnData").Where(a =>a.Attribute("colNum").Value == value))
        {
            yield return selected.Element("data").Value;
        }

usage will change based on how you want it 用法将根据您的需要而改变

The easiest way is to use XPathSelectElement. 最简单的方法是使用XPathSelectElement。 Assuming that reportDataRow is an XElement representing the root element, and value is a variable that you want to match the colNum attribute with: 假设reportDataRow是一个表示根元素的XElement,而value是一个要与colNum属性匹配的变量:

reportDataRow.XPathSelectElement(".//data[parent::columnData/@colNum = '" + value + "']");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM