0

我有一个如下的 XML 文件。

<BOOK bnumber="1" bname="Book">
    <CHAPTER cnumber="1">
       <Sentence vnumber="1">This is the sentence 1.</Sentence>
       <Sentence vnumber="2">This is the sentence 2.</Sentence>
       <Sentence vnumber="3">This is the sentence 3.</Sentence>
   </CHAPTER>
   <CHAPTER cnumber="2">
       <Sentence vnumber="1">Hello World 1.</Sentence>
       <Sentence vnumber="2">Hello World 2.</Sentence>
       <Sentence vnumber="3">Hello World 3.</Sentence>
       <Sentence vnumber="4">Hello World 4.</Sentence>
  </CHAPTER>
  <CHAPTER cnumber="3">
       <Sentence vnumber="1">Good morning 1.</Sentence>
       <Sentence vnumber="2">Good morning 2.</Sentence>
       <Sentence vnumber="3">Good morning 3.</Sentence>
  </CHAPTER>
</BOOK>

我想要的是收集“CHAPTER”的属性。目标是得到

Chapter={"Chapter 1";"Chapter 2","Chapter 3"};

目前我使用传统方法,

XmlDocument xdoc = new XmlDocument();
xdoc.Load(@"C:\books.xml"); //load the xml file into our document
XmlNodeList nodes = xdoc.SelectNodes(@"//BOOK/CHAPTER[@cnumber='" + chap
string sentences = "";
foreach(XmlNode node in nodes) {
   sentences += node.InnerText + "; ";
}

但我想使用 XMLReader 因为 XML 文件很大,我不想将它加载到内存中。

感谢帮助。

4

1 回答 1

1

那么基本上你可以这样做:

        var chapters = new List<string>();
        using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
        {
            reader.ReadToFollowing("CHAPTER");
            reader.MoveToFirstAttribute();
            string chapterNumber = reader.Value;
            chapters.Add("Chapter " + chapterNumber);
        }

其中 xmlString 是您的 xml。

这将找到第一章并从中获取属性并将其添加到章节列表中。

于 2012-07-05T13:03:36.527 回答