簡體   English   中英

C#XML根據屬性獲取節點

[英]C# XML get nodes based on attribute

我有以下xml:

<root ...>
  <Tables>
    <Table content="..">
    </Table>
    <Table content="interesting">
      <Item ...></Item>
      <Item ...></Item>
      <Item ...></Item>
    </Table>
    ...etc...
  </Tables>
</root>

我正在使用以下代碼從“有趣的”節點獲取項目:

XElement xel = XElement.Parse(resp);

var nodes = from n in xel.Elements("Tables").Elements("Table")
            where n.Attribute("content").Value == "interesting"
            select n;

var items = from i in nodes.Elements()
            select i;

有沒有更簡單,更清潔的方法來實現這一目標?

好吧,對items使用查詢表達式毫無意義,並且您可以非常輕松地將整個內容包裝在單個語句中。 我什至不會為查詢表達式而煩惱:

var items = XElement.Parse(resp)
                    .Elements("Tables")
                    .Elements("Table")
                    .Where(n => n.Attribute("content").Value == "interesting")
                    .Elements();

請注意,此操作(和您當前的查詢)將為任何沒有content屬性的Table元素引發異常。 如果您只想跳過它,則可以使用:

.Where(n => (string) n.Attribute("content") == "interesting")

代替。

您可以使用XPath(擴展名在System.Xml.XPath命名空間中)在一行中選擇所有項:

var items = xel.XPathSelectElements("//Table[@content='interesting']/Item");

如果您不需要查詢之外的nodes來查詢items ,則可以執行以下操作:

var items = from n in xel.Elements("Tables").Elements("Table")
            where n.Attribute("content").Value == "interesting"
            from i in n.Elements()
            select i;

使用xml文件
XmlDocument xdoc =新的XmlDocument();

var item = xdoc.GetElementsByTagName(“ Table [@ content ='interesting'] / Item”);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM