簡體   English   中英

如何從 XML 中的元素中獲取特定元素字符串?

[英]How to get specific element string from element in XML?

我有這個 XML 文件,我想只用文章 ID 和 item_description值填寫我的列表。

 <?xml version="1.0" encoding="utf-8"?> <articles> <article id="i1"> <item_description>Mobitel Smasung</item_description> <single_price>Kom</single_price> <unit_of_measure>1250</unit_of_measure> </article> <article id="i2"> <item_description>Mobitel DA</item_description> <single_price>WD</single_price> <unit_of_measure>232</unit_of_measure> </article> </articles>

這是我到目前為止得到的:

 public void LoadAllArticles() { XDocument xdoc = XDocument.Load(defaultDataPath + @"\saved_articles.xml"); foreach (var article in xdoc.XPathSelectElements("articles/article")) { articles = article.Descendants().Select(element => element.Value).ToList(); } }

如何僅將id + " " + item_description 加載到列表中?

由於您需要父articleid屬性,因此將對Descendants()的調用移至Select() lamdba 以執行字符串連接(跳過 foreach 循環):

    articles = xdoc.XPathSelectElements("articles/article")
                   .Select(art => art.Attribute("id").Value + " " + art.Descendants().FirstOrDefault(node => node.Name == "item_description", "<no description>"))
                   .ToList();

暫無
暫無

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

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