0

我有这个 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 加载到列表中?

4

1 回答 1

0

由于您需要idparent 的属性,因此article将调用移动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();
于 2022-01-11T12:17:59.123 回答