0

I am reading an XML using XMLTextReader in C#.net. The structure of XML is like below:

<root attr1="" attr2="">
    <element1>some value</element1>
    <element2>some value</element2>
</root>

After reding attributes, I shift control to element1. Code is as below:

reader.MoveToElement()
if(reader.ReadToDecedent("element1"))
{
    string val= reader.ReadInnerXML();
}

Now after reading this, reader shows whites space. Again I want to move to element1 and from there, using ReadToDecendent I want to move to element2. I cannot use MoveToContent() as I have to follow the same flow.

So how can I move to element1 after reader inner text?

1 Answer 1

0

Have you considered using XPathDocument and the related classes? It would look like such:

var _xml = "<xml><elements><element1>some text</element1><element2>some more text</element2></elements></xml>";
var xPathDoc = new XPathDocument(XmlReader.Create(new StringReader(_xml)));
var nav = xPathDoc.CreateNavigator();
var node = nav.SelectSingleNode("//element1");  // with xpath exp you can pick out specific tags
var innerText = node.Value;

Now if you just had element as the name of the tags instead of element1, element2,... you can iterate through all element tags:

var nodes = nav.Select("//element");  // selects all element tags
while(nodes.MoveNext()){
    //do something
}

This is probably a simpler way to query a xml doc. Plus, if you wanted tags that had a specific attribute, the xpath expression would be //element[attr1=\"atrribute_value\"]

Hope this helps

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.