【问题标题】:XmlReader: Read sub elementsXmlReader:读取子元素
【发布时间】:2014-05-31 13:49:41
【问题描述】:

我有这种 XML

...
<config>
  <parameters>
    <location attribute1="toto" attribute2="anotherThing"/>
    <other attribute1="toto" attribute2="anotherThing"/>
    <other2 attribute1="toto" attribute2="anotherThing"/>
  </parameters>
</config
...

(请注意,这是一个非常愚蠢的例子,我理解这对于具体数据可能没有意义)。

我的 XmlReader 目前在 parameters 节点上,我想读取所有子元素(直到我看到 &lt;/parameters&gt;

如何使用 XmlReader 检索它? (因为我在更大的框架中,所以必须使用 XmlReader)。

谢谢。

【问题讨论】:

  • XmlReader.ReadSubTree 将是我的第一个停靠港。
  • @Dmitry 是的,我可以这样做,但在我的真实情况下,我有 20 多个可能的孩子类型,所以我更喜欢阅读它们,然后查看它们对应的内容而不是尝试阅读很多东西不在这里。
  • @TonyHopkinson:我去看看这个方法,谢谢!

标签: c# .net xml parsing xmlreader


【解决方案1】:

以下代码会将&lt;parameters&gt; 的所有子注释写入 StringBuilder 命名输出,这应该会提示您使用 XmlReader 处理 xml:

代码

StringBuilder output = new StringBuilder();

using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
    bool seenParam = false;

    XmlWriterSettings ws = new XmlWriterSettings();
    ws.Indent = true;
    using (XmlWriter writer = XmlWriter.Create(output, ws))
    {
        // Parse the file and write each of the nodes.
        while (reader.Read())
        {
            // Did we've seen the a node named parameters?
            if (reader.NodeType == XmlNodeType.Element && reader.Name == "parameters")
                seenParam = !seenParam;

            // If not, proceed with the next node
            if (!seenParam)
                continue;

            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    writer.WriteStartElement(reader.Name);
                    writer.WriteAttributes(reader, false);
                    break;
                case XmlNodeType.Text:
                    writer.WriteString(reader.Value);
                    break;
                case XmlNodeType.XmlDeclaration:
                case XmlNodeType.ProcessingInstruction:
                    writer.WriteProcessingInstruction(reader.Name, reader.Value);
                    break;
                case XmlNodeType.Comment:
                    writer.WriteComment(reader.Value);
                    break;
                case XmlNodeType.EndElement:
                    writer.WriteFullEndElement();
                    break;
            }
        }
    }
}

输出

<parameters>
  <location attribute1="toto" attribute2="anotherThing">
    <other attribute1="toto" attribute2="anotherThing">
      <other2 attribute1="toto" attribute2="anotherThing"></other2>
    </other>
  </location>
</parameters>

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    相关资源
    最近更新 更多