0

I have an XML file as below.

<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>

What I want is to collect the attributes of "CHAPTER". The goal is to get

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

Current I use tradition method,

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 + "; ";
}

but I want to use XMLReader because the XML file is big, I don't want to load it in memory.

Thanks for help.

2
  • Have you tried writing any code againt the XMLReader yet? Commented Jul 5, 2012 at 12:53
  • Not yet, I am not strong on it. Commented Jul 5, 2012 at 12:55

1 Answer 1

1

Well basicly you can do like this:

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

where the xmlString is your xml.

This will find the first chapter and get the attribute from it and add it to a list of chapters.

Sign up to request clarification or add additional context in comments.

3 Comments

the xmlString is MY xml, but is it big. Say 20MB. Can we do in this way?
XmlReader.Create also has an overload that can take any Stream object. That is what you will want to do. Create a stream which will read from the XML source, then pass that stream to the Create method instead of a new StringReader (e.g. XmlReader.Create(myStream)).
I meant that does xmlString refer to the entire xml file here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.