简体   繁体   English

如何使用 XmlReader 读取 xml 文档?

[英]How to read xml document with XmlReader?

I have a xml:我有一个 xml:

<doc>
****
<book>
    <author>Pete</author>
    <rating>4</rating>
    <pages>243</pages>
</book>
<shop>
    <></>
    <></>
</shop>
</doc>

I tried to read it with XmlReader:我试着用 XmlReader 阅读它:

using (XmlReader reader = XmlReader.Create(stream))
{
    reader.MoveToContent();
    //read some elements
    reader.ReadToFollowing("book");

}

But when i meet element book i dont know how to move inside, i mean how to read author , rating etc?但是当我遇到元素book我不知道如何进入内部,我的意思是如何阅读authorrating等? And how to move to upper level again to read shop element.以及如何再次移动到上层以读取shop元素。
I tried ReadToDescendant() but dont think that its what i needed.我试过ReadToDescendant()但不认为这是我需要的。
Any advises?任何建议?

Examples from comments dont helped me.评论中的例子对我没有帮助。 I forget that i have a namespaces in document:我忘了我在文档中有一个命名空间:

<doc>
  ****
  <book>
      <ns8:author>Pete</ns8:author>
      <ns8:rating>4</ns8:rating>
      <ns8:pages>243</ns8:pages>
  </book>
  <shop>
      <></>
      <></>
  </shop>
</doc>

So i use NamespaceManager:所以我使用 NamespaceManager:

  var nsmgr = new XmlNamespaceManager(reader.NameTable);
  nsmgr.AddNamespace("ns8", "namespace uri1");
  nsmgr.AddNamespace("ns6", "namespace uri2");

And read document:并阅读文档:

using (XmlReader reader = XmlReader.Create(stream))
{
   while (reader.Read())
   {
       if (reader.NodeType == XmlNodeType.Element)
       {
           reader.ReadToFollowing("book");
           reader.ReadToFollowing("ns8:author");
       }
}

But anyway line reader.ReadToFollowing("ns8:author");但无论如何 line reader.ReadToFollowing("ns8:author"); do not return author node.不返回author节点。

Specify the right namespace in the ReadToFollowing method.ReadToFollowing方法中指定正确的命名空间。

using (XmlReader reader = XmlReader.Create(stream))
{
    reader.ReadToFollowing("book");

    reader.ReadToFollowing("author", "uri1");
    var author = reader.ReadElementContentAsString();
    Console.WriteLine(author);

    reader.ReadToFollowing("rating", "uri1");
    var rating = reader.ReadElementContentAsInt();
    Console.WriteLine(rating);

    // and so on
}

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

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