【问题标题】:Reading specific element from xml从 xml 读取特定元素
【发布时间】:2021-03-30 07:26:44
【问题描述】:

我觉得这真的很愚蠢,但似乎无法弄清楚。

我有一个从 XML 文件填充的组合框,效果很好。 现在我想在选择一个项目时显示一个特定的元素(描述),但字符串总是想返回 null。

XML:

<?xml version="1.0" encoding="utf-8" ?>
<Barbarian>
  <Special id="Lesser Ancestor Totem">
    <SpecialName>Lesser Ancestor Totem</SpecialName>
    <Description>Gain a +2 Insight Bonus to a skill (that you can use while raging) while raging</Description>
  </Special>
</Barbarian>

获取描述并放入 RichTextBox 的代码:

 public void LoadFeatDescription()
        {
            string Class = CharClassSelector.Text;
            string Feat = FeatPicker.Text;

            XDocument doc = XDocument.Load($"\\Xml\\Classes\\{Class}.xml");

            string description = doc.XPathSelectElement($"//Special[@id='{Feat}']/Description").Value;
            //the string description wants to stay null despite my efforts
            DescriptionBox.Text = description;
                 
        }

这个想法是,这将加载一个特定的文件并根据 id 获取描述元素。 我错过了什么愚蠢的东西吗?

谢谢!

编辑:在整个 XML 内容中添加

【问题讨论】:

  • 您是显示整个 xml 还是只显示其中的一部分? xml 中有命名空间吗?
  • @AlexanderPetrov 我确实忽略了根。 ``` Lesser Ancestor Totem在狂暴时获得+2洞察奖励(你可以在狂暴时使用)描述> ``` 但是即使把它放在 XpathSelectElement 中也会产生一个空值。
  • 使用如下:string description = (string)doc.Descendants("Description").FirstOrDefault();
  • @jdweng 这确实得到了描述,但仅限于第一个。当我尝试再添加时,它只会显示第一个。我需要能够根据 id 获取项目的描述。
  • 更改:string[] description = doc.Descendants("Description").Select(x => (string)x).ToArray();

标签: c# xml xpath


【解决方案1】:

我明白了。

已更改string description = doc.XPathSelectElement($"//Special[@id='{Feat}']/Description").Value;string description = (string)doc.XPathSelectElement($"//Special[@id='{Feat}']/Description").Value;

我知道这很愚蠢......

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多