简体   繁体   English

在使用C#解释不包含内容的元素时,如何从XML(包含后代)读取兄弟元素的内容?

[英]How can I read the contents of sibling elements from XML (with descendants) while accounting for elements with no content using C#?

I am trying to read the contents of an XML file and store it in various lists, however, where I keep running into trouble is trying to read the sibling nodes that are not the innermost child nodes (siblings 1-4 and tableName below). 我试图读取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>

I can't use ReadElementContentAs because they have descendants, and I found a way to code around it, but I still run into trouble if I encounter an element that has no content (such as table name above). 我不能使用ReadElementContentAs因为它们具有后代,并且找到了一种围绕它进行编码的方法,但是如果遇到没有内容的元素(例如上面的表名),仍然会遇到麻烦。 If the element has no content (and it could or could not have content), my code solution (example for tableName seen below) doesn't work and the program crashes because it's looking for the wrong kind of node. 如果该元素不包含任何内容(并且可能包含或不包含内容),则我的代码解决方案(如下所示的tableName的示例)不起作用,并且程序崩溃,因为它正在寻找错误类型的节点。 Is there an easier way to access the content of these siblings or a way to account for the fact that the element could have no content? 有没有更简单的方法来访问这些兄弟姐妹的内容,或者是一种解决该元素可能没有内容的事实的方法? I'm new to XML so I'm unsure of all the different methods. 我是XML的新手,所以不确定所有不同的方法。 Thanks! 谢谢!

// 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();

You have to check the type of the node before reading it or moving inside. 在读取或移入节点之前,您必须检查节点的类型。

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}'");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM