【问题标题】:How to get specific element string from element in XML?如何从 XML 中的元素中获取特定的元素字符串?
【发布时间】:2022-01-11 12:07:20
【问题描述】:

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

【问题讨论】:

    标签: c# xml element nsxmlelement


    【解决方案1】:

    由于您想要来自父 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();
    

    【讨论】:

    • 这样我得到“XElement 不包含 Select 的定义”
    • @SebastianMarjanović 抱歉,我遗漏了一个重要细节,您需要在整个文章元素集合上使用Select(),答案已更新
    • 非常感谢,会试一试!是处理 xml 文件的新手
    • 输出是 i1 Mobitel Šmasung,有没有其他方法可以删除标签,或者我应该只是 string.Replace();
    • @SebastianMarjanović .Value 最后应该只给你内部文字:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2018-04-25
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多