【问题标题】:Nested Xml Nodelists in C#C# 中的嵌套 Xml 节点列表
【发布时间】:2019-08-14 00:09:22
【问题描述】:

我正在尝试隔离下面 XML 中每个 <question> 元素中的 <string> 元素。 我使用了我最熟悉的 Xpath。基本上,我使用SelectNodes("question"),如果指向下面的 XML,它将返回正确的 5 个元素。然后我想迭代每个<question> 中的<string> 元素。 我不想直接转到“问题/字符串”,因为它将返回 XML 文件中的所有 <string> 实例。在此处未包含的某个问题中,我有一些工作要做,实际文件比这要复杂得多,但这就是我正在努力解决的问题。

这是我使用的代码。它返回文件的所有<string> 元素,而不仅仅是我在任何给定时刻正在使用的节点。

XmlNodeList questions = doc.SelectNodes("//question");
string question = null;
foreach (XmlElement qquestion in questions) //I also tried XmlNode here
{
  XmlNodeList qstrings = qquestion.SelectNodes("//string");
  foreach (XmlNode qstring in qstrings)
  {
    question = qstring.InnerText; //There's a lot more processing I'll do here
  }
 }

这是我的简化 XML。感谢您的任何指示。

<content version="1.0">
    <question>
      <string>Question 1 part 1</string>
      <string>Question 1 part 2</string>
      <graphic scale=".8" align="center" yOffset="-50" xOffset="50" asset="Numline_Triangle"/>
      <graphic scale="1.2" align="center" yOffset="20" asset="Numline_Shapes_0_40"/>
    </question>
    <question>
      <string>Question 2</string>
      <graphic scale=".8" align="center" yOffset="-50" xOffset="50" asset="Numline_Square"/>
      <graphic scale="1.2" align="center" yOffset="20" asset="Numline_Shapes_0_40"/>
    </question>
    <question>
      <string>Question 3 part 1</string>
      <string>Question 3 part 2</string>
      <graphic scale=".8" align="center" yOffset="-50" xOffset="50" asset="Numline_Square"/>
      <graphic scale="1.2" align="center" yOffset="20" asset="Numline_Shapes_60_100"/>
    </question>
    <question>
      <string>Question 4</string>
      <graphic scale=".8" align="center" yOffset="-50" xOffset="50" asset="Numline_Circle"/>
      <graphic scale="1.2" align="center" yOffset="20" asset="Numline_Shapes_60_100"/>
    </question>
    <question>
      <string>Question 5</string>
      <graphic scale=".8" align="center" yOffset="-50" xOffset="50" asset="Numline_Triangle"/>
      <graphic scale="1.2" align="center" yOffset="20" asset="Numline_Shapes_60_100"/>
    </question>
  </content>

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    它返回文件的所有&lt;string&gt; 元素,而不仅仅是我在任何给定时刻正在使用的节点。

    是的。这是正确的行为,因为//string 返回所有全局 存在的string 元素。

    要仅返回所有 descendant string 元素,只需在 XPath-1.0 表达式的开头添加 .,如下所示:

    ...
    XmlNodeList qstrings = qquestion.SelectNodes(".//string");
    foreach (XmlNode qstring in qstrings)
    {
      question = qstring.InnerText; //There's a lot more processing I'll do here
    }
    ...
    

    表达式.//string 返回所有string 元素,它们是当前qquestion XmlNode 的后代。

    【讨论】:

    • 太棒了,我知道这很简单,但无法弄清楚。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多