eminence / xmltree-rs

Reads an XML file into a simple tree structure
MIT License
39 stars 31 forks source link

Documentation On How to Iterate Through a Series of XML Elements and Make Objects Out of Those Elements. #9

Closed AlexCreamer closed 7 years ago

AlexCreamer commented 7 years ago

For example, how could I iterate through the following xml elements and extract each text: <tag1>text1</tag1><tag1>text2</tag1><tag1>text3</tag1><tag1><tag2>text4</tag2></tag1>

eminence commented 7 years ago

You can't parse this as written. XML requires that there is exactly 1 root element. So you would have to wrap this whole thing in another element. For example:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<tags>
  <tag1>text1</tag1>
  <tag1>text2</tag1>
  <tag1>text3</tag1>
  <tag1>
     <tag2>text4</tag2>
  </tag1>
</tags>

And this could be parsed like so:

let e = Element::parse(data.as_bytes()).unwrap();
for child in e.children {
    println!("Tag {} has value {:?}", child.name, child.text);
    if child.children.len() > 0 {
        println!("  This tag has {} children", child.children.len());
    }
}

Which would give the following output:

Tag tag1 has value Some("text1")
Tag tag1 has value Some("text2")
Tag tag1 has value Some("text3")
Tag tag1 has value None
  This tag has 1 children
eminence commented 7 years ago

Does this answer your question?

AlexCreamer commented 7 years ago

It does, thank you.

eminence commented 7 years ago

Great, let me know if you have any other questions.