【问题标题】:How can I read the contents of sibling elements from XML (with descendants) while accounting for elements with no content using C#?如何在使用 C# 考虑没有内容的元素时从 XML(带有后代)读取兄弟元素的内容?
【发布时间】:2026-02-23 16:10:01
【问题描述】:

我正在尝试读取 XML 文件的内容并将其存储在各种列表中,但是,我一直遇到麻烦的是尝试读取不是最内层子节点的兄弟节点(兄弟节点 1-4 和 tableName下面)。

<Parent parent="1">
  <sibling1>256</sibling1>
  <sibling2>1000</sibling2>
  <sibling3>25</sibling3>
  <sibling4 id="1">
    <tableName></tableName>
    <table id="0">
      <row id="0">
        <child1></child1>
        <child2>0</child2>
        <child3>default</child3>
      </row>
    </sibling4>
</Parent>

我不能使用ReadElementContentAs,因为它们有后代,并且我找到了一种绕过它的编码方法,但是如果遇到没有内容的元素(例如上面的表名),我仍然会遇到麻烦。如果元素没有内容(它可能有内容,也可能没有内容),我的代码解决方案(如下所示的 tableName 示例)不起作用并且程序崩溃,因为它正在寻找错误类型的节点。有没有更简单的方法来访问这些兄弟元素的内容,或者有一种方法可以解释元素可能没有内容的事实?我是 XML 新手,所以我不确定所有不同的方法。谢谢!

// tableName - WILL NOT WORK IF TABLE NAME IS LEFT BLANK (MUST HAVE DEFAULT)
xmlIn.ReadToDescendant("tableName");
xmlIn.Read();
List.tableName = xmlIn.Value;
xmlIn.Read();
xmlIn.ReadEndElement();

【问题讨论】:

  • 举个例子说明你想获取什么数据。

标签: c# xml xml-parsing xmlreader


【解决方案1】:

在读取或移动之前必须检查节点的类型。

while (reader.Read())
{
    if (reader.NodeType == XmlNodeType.Element && reader.LocalName.StartsWith("sibling"))
    {
        Console.Write(reader.LocalName + ": ");
        reader.Read();

        if (reader.NodeType == XmlNodeType.Text)
            Console.WriteLine(reader.ReadContentAsString());
        else
        {
            reader.ReadToFollowing("tableName");
            Console.Write(reader.LocalName + ": ");
            var tableName = reader.ReadElementContentAsString();
            Console.WriteLine($"'{tableName}'");
        }
    }
}

【讨论】:

    最近更新 更多