Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
How to check whether all the Xml tag are formed in the following order using XMLReader

XML
<Model>
<Object type="Book">
<Component id="123">
<Element id="123">
<Article>
</Article>
<Article >
</Article>
</Element>
</Component>
</Object>
</Model>


Here Article node doesn't have any attributes.

I need to count the Object Node having attribute type="Book" and tag as formed above.

If the tag follows the above structure a book should be counted.

How to do this if XML contains 12000 lines.


Here is the code I've tried

C#
XMLReader reader=new XMLReader(filePath);
bool inObject=false;
bool inComponent=false;
bool inElement=false;

int bookCount=0;

while(reader.read())
{
if(reader.LocalName="Object" && !inObject)
{
inObject=true;
}
if(reader.LocalName="Component" && inObject==true)
{
inComponent=true;
}
if(reader.LocalName="Element" && inComponent==true)
{
inElement=true;
}
if(reader.LocalName=="Article" && inElement==true)
{
bookCount++;
inObject=false;
}
}

}


Its not working Please help me
Posted

1 solution

For well-formedness I simply try to load it into an XmlDocument and catch the Exception.

You may be looking to validate against a schema; that's a whole different matter.

But to keep it simple, rather than do what you have, look into XPath : /Model/Object[@type='Book' and Component/Element/Article] .


System.Xml.XmlDocument doc = new System.Xml.XmlDocument() ;
doc.Load ( "Book.xml" ) ;
System.Console.WriteLine ( doc.SelectNodes ( "/Model/Object[@type='Book' and Component/Element/Article]" ).Count ) ;
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900