簡體   English   中英

使用Linq從xml獲取屬性

[英]Getting attributes from xml using Linq

我有一個XML文檔,我想從中獲取屬性

這是XML:

<Translations>
   <Product Name="Room" ID="16">
      <Terms>
         <Term Generic="Brand" Product="Sub Category" />
         <Term Generic="Range" Product="Brand" />
      </Terms>
   </Product>
   <Product Name="House"" ID="29">
      <Terms>
          <Term Generic="Category" Product="Product Brand" />
          <Term Generic="Brand" Product="Category Description" />
          <Term Generic="Range" Product="Group Description" />
          <Term Generic="Product" Product="Product Description" />
      </Terms>
   </Product>
</Translations>

這是我當前的Linq查詢

public static string clsTranslationTesting(string GenericTerm, int ProductID)
{
    const string xmlFilePath = "C:\\Dev\\XMLTrial\\XMLFile1.xml";
    var xmlDocument =  XDocument.Load(xmlFilePath);
    var genericValue =
        from gen in xmlDocument.Descendants("Product")
        where gen.Attribute("ID").Value == ProductID.ToString()
        select gen.Value.ToString();
}

我遇到的錯誤是當我將數據傳遞到方法中時,該方法將xml從文件成功加載到xmlDocument變量。 但是,當執行查詢時,它將返回空值。 我想獲取ID值。

您的問題讓我有些迷惑,但這是我的嘗試。

首先,您需要將“客戶”更改為“產品”。 您的XML並不包含單詞“ Customer”的單個實例,因此我認為您那里有一個錯字。

我不知道您要從查詢中返回什么(我只是假設整個匹配的節點?)。 嘗試這個:

var genericValue = xmlDocument.Descendants("Product")
                       .FirstOrDefault(x => x.Attribute("ID").Value == "16");

我在這里做了一個小提琴,展示了它的作用

暫無
暫無

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

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