XmlReader:读取子元素

时间:2014-04-16 15:23:06

标签: c# .net xml parsing xmlreader

我有这种XML

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

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

我目前在parameters节点上使用我的XmlReader,我想阅读所有子元素(直到我看到</parameters>

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

谢谢。

1 个答案:

答案 0 :(得分:0)

以下代码将<parameters>的所有子注释写入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>