tags:

views:

662

answers:

3

Hi all,

I'm using XmlReader and xml navigator as following:

XmlDocument doc = new XmlDocument();
doc.Load(txtFileName.Text.Trim());
// Create the navigator.

XPathNavigator xnav = doc.CreateNavigator();

Once you created the navigation you can select the descendant or children and you can determine the number of childrens. However, i have problem which is when i need to know the number of attributes of that node i can't for example if you want to know the number of childrens you use the following code.

int size = xnav.SelectDescendants(XPathNodeType.All, true).Count;

This function accepts two parameters in this case: the type of Nodes you want to be selected like text comment or element and the second parameter is set to true if you want the root of this subtree which is the current node to be selected as well as a part of the subtree.

The result of select[*] is XPathIterator object.

Of course you don't want the count of comments or white space in general so you don't use the all attribute to retrieve all the node but you need to specify the type of nodes you want lets say we need all elements, attributes and text therefore we should run the following command:

int size = xnav.SelectDescendants(XPathNodeType.Attribute | XPathNodeType.Element | XPathNodeType.Text , true).Count;

i think that you need the value of the attribute to be counted as well so you have to double the result of attributes count more over it is not working to specify the type of Nodes like this so i made the following:

int size = (xnav.SelectDescendants(XPathNodeType.Attribute, true).Count * 2) +
    xnav.SelectDescendants(XPathNodeType.Element, true).Count +
    xnav.SelectDescendants(XPathNodeType.Text , true).Count;

Currently i have the count of all the above except the attribute i have no count for that.

HEEELLLPPP!!! please

p.s. i don't want to go through a loop to elements it is very costly to do so.

A: 

I will do it manually, from string

<img src="" style="" width=""/>

Just count the "=" sign and that's it

pixel3cs
I'm not sure that will work.... <xmlElement myValue="sometext=sometxt"/>
Greg
... or <code>var matches = (someVar==someOtherVar)</code>
Dour High Arch
+1  A: 

If you are really worried about performance, you should use the XmlReader to do this directly, and not be doing all of these XPath queries. It would also have the benefit that you could track all of your counts at once, rather than performing several document-wide queries.

PeterAllenWebb
A: 

You could use xpath to find out how many attributes there are

XmlDocument doc = new XmlDocument();
doc.Load(txtFileName.Text.Trim());
XPathNavigator xnav = doc.CreateNavigator();
xnav.Evaluate("count(//@*)");
Greg