Find the depth of XML

I have following XML:
How can I find the depth of XML?
in other word max level of the XML 

<Root> ----- level  0
<Name>----- level 1
     <FirstName>name</FirstName> ---- level 2
     <LasName>lname</LastName>
     <MiddleName>mName<MiddleName>
</Name>
<Information>
      <Info1>
             <Info2> --- level 3
                       <Info3>asdasd</Info> -- level 4
              </Info2>          
      </Info1>

</Information>
</Root>
0
6/5/2005 2:49:04 PM
dotnet.xml 7266 articles. 0 followers. Follow

2 Replies
540 Views

Similar Articles

[PageSpeed] 49


Raed Sawalha wrote:

> I have following XML:
> How can I find the depth of XML?
> in other word max level of the XML 
> 
> <Root> ----- level  0
> <Name>----- level 1
>      <FirstName>name</FirstName> ---- level 2
>      <LasName>lname</LastName>
>      <MiddleName>mName<MiddleName>
> </Name>
> <Information>
>       <Info1>
>              <Info2> --- level 3
>                        <Info3>asdasd</Info> -- level 4
>               </Info2>          
>       </Info1>
> 
> </Information>
> </Root>

XmlTextReader has a Depth property which you could store, however note 
that with that approach the text node inside of the <Info3> element is 
on level (or depth) 5:

     XmlTextReader xmlReader = new XmlTextReader(@"test2005060501.xml");
     int maxDepth = 0;
     while (xmlReader.Read()) {
       if (xmlReader.Depth > maxDepth) {
         maxDepth = xmlReader.Depth;
       }
       Console.WriteLine(
"Node type: {0}, node name: {1}, node depth: {2}.", xmlReader.NodeType, 
xmlReader.Name, xmlReader.Depth);
     }
     Console.Write("Maximum depth is: {0}.", maxDepth);

If you do not want to count text nodes or comment nodes you need to 
check the NodeType and only change maxDepth for the node types you are 
looking for.


-- 

	Martin Honnen --- MVP XML
	http://JavaScript.FAQTs.com/
0
mahotrash (1777)
6/5/2005 3:29:27 PM
> How can I find the depth of XML?
> in other word max level of the XML

Using XSLT 1.0 this can be done in the following way:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/">
   <xsl:for-each select="//node()[not(node())]">
     <xsl:sort select="count(ancestor::node())"
          data-type="number" order="descending"/>

     <xsl:if test="position()=1">
       <xsl:value-of select="count(ancestor::node())"/>
     </xsl:if>
   </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>


Using XPath 2.0 one could write a single XPath expression which evaluates to 
the maximum depth of the source xml document:

        max(//*[not(*)]/count(ancestor::node()))

And the following XPath 2.0 expression selects all nodes that are at maximum 
depth:


//*[not(*)][count(ancestor::node())
                  =
                    max(//*[not(*)]/count(ancestor::node()))
                    ]



Cheers,
Dimitre Novatchev

"Raed Sawalha" <RaedSawalha@discussions.microsoft.com> wrote in message 
news:04CCC1B1-CAFE-4567-9CEE-C5103098D11D@microsoft.com...
>I have following XML:
> How can I find the depth of XML?
> in other word max level of the XML
>
> <Root> ----- level  0
> <Name>----- level 1
>     <FirstName>name</FirstName> ---- level 2
>     <LasName>lname</LastName>
>     <MiddleName>mName<MiddleName>
> </Name>
> <Information>
>      <Info1>
>             <Info2> --- level 3
>                       <Info3>asdasd</Info> -- level 4
>              </Info2>
>      </Info1>
>
> </Information>
> </Root> 


0
6/5/2005 8:59:07 PM
Reply:

Similar Artilces:

KnowledgeBase is not working-where do I find Payroll year end chec
Can anyone let me know where to find the Payroll year end checklist document usually found in the Knowledgebase? It doesnt matter what I search for , the results and empty. -- Doug I think you want KB850663 https://mbs.microsoft.com/knowledgebase/KBDisplay.aspx?WTNTZSMNWUKNTMMYMXTYYKSWTLKQNNOXWZLPVYTMYYOXZZNUPLRTMYQZKVQUMOWM --- D. Valade First Tech Direct, LLC http://www.firsttechdirect.com "Doug" wrote: > Can anyone let me know where to find the Payroll year end checklist document > usually found in the Knowledgebase? > > It doesnt matter what I search for , ...

xml to text ???
hi everyone i wish to ask if anyone can help mi to convert a XML file to a normal text file that does not contain the tags and header.. i just want the information of the columns .. thanks in advance chris -- Message posted via http://www.dotnetmonster.com "chris ong via DotNetMonster.com" <forum@nospam.DotNetMonster.com> wrote in message news:b9b5e2cec4b547ba89bbd11056c8062a@DotNetMonster.com... > i wish to ask if anyone can help mi to convert a XML file to a normal text > file that does not contain the tags and header.. i just want the > information of the colu...

Flat File/XML
If I have a flat file, and an XSD, is it possible to convert the delimited flat file to XML? Thanks, Stephen Andrews platinumbay wrote: > If I have a flat file, and an XSD, is it possible to convert the delimited > flat file to XML? > > Thanks, > > Stephen Andrews Given an appropriate XSD filter you should be able to parse a flat file. However, XSD is not really the best approach; try a parser generator like the Lex/Yacc combination. Hi Stephen, First of all, I would like to confirm my understanding of your issue. I'm not quite sure what you need to do. Do you ...

Find Next -- Only Works First Time
I have a form where I give the user a button to click to bring up the Microsoft Find and Replace Dialog Box. When the user clicks Find Next they can find the first instance of the string they are searching for. However, the next time the user hits Find Next the user gets the message that the string is not found, even when a second instance of the string exists in the set of records being searched. The code I use, and have used previously successfully in Access, is: Screen.PreviousControl.SetFocus DoCmd.DoMenuItem acFormBar, acEditMenu, 10, , acMenuVer70 On difference (I am not sure it ma...

Find variable unique text within a string
Hi. I have a large spreadsheet where I have listed System number vertically and horisontally in a Matrix. What I want to do is to identify / mark which record in the vertical listing of these system numbers that are listed in column C (Links) Starting in Column D1 I have used the following function and copied it across the matrix : =IF(ISNUMBER(SEARCH(D$1,$C2)),"Yes","") The spreadsheet looks like this: A B C D E F "System" "Description" &quo...

Finding formulas
Do you have a formula or something that I can use in conditional format to tell if a cell contains a formula. >-----Original Message----- >Do you have a formula or something that I can use in >conditional format to tell if a cell contains a formula. >. You could use this macro Sub test() Selection.SpecialCells(xlFormulas).Select With Selection.Interior .ColorIndex = 6 .Pattern = xlSolid End With Range("A1").Activate End Sub Peter Atherton Copy/paste this UDF to a general module in your workbook. Function IsFormula(cell) Application.Vol...

Creating a message to find my posts
Sorry, but I am creating this just so I can find my posts on here by clicking on my name within this post. Can't see any other way. I search for the title - nothing comes up, I search for my user name - nothing comes up. Notify me of replies doesn't work! Click on this link: http://groups.google.com/groups/search?enc_author=3D3Qz8RCEAAAArhhjrMG_fyPf= LngCqP6Bi2p5MNQxqBUIP2AeqP4W-7pHRGrMdZImE0Gr1e5nVtd0&scoring=3Dd Add it to your favourites - it should be dynamic. Hope this helps. Pete On Dec 15, 9:11=A0am, imacken <imac...@discussions.microsoft.com> wr...

Can't find "My Computer"
Hi. I've tried sending this question but I never see . I am using Window Vista and can not find the screen that says "My Computer" I've looked everywhere. Can you help me find this window? -- Jolley Noonan In news:8D91AC41-95A9-4704-92B2-9ECD9944749A@microsoft.com, jolley noonan wrote: > Hi. I've tried sending this question but I never see . I am using > Window Vista and can not find the screen that says "My Computer" > I've looked everywhere. Can you help me find this window? InVista, it's just called "Computer". Are you ...

Xml Attribute..id problem??
Hi, I have an xml file as below <root> <table id =1> <user>abc</user> <age>25</age> </table> <table id = 2> <user>xyz</user> <age>45</age> </table> ..... ..... </root> What I want is this id attribute to increment automatically. So I declared it of type "ID" ..but how do i access the value of this attribute. When i add a record it gets added to the xml file but the id attribute does not show..So how do i refer to this attribute. smita wrote: > What I want is this id attribute to incre...

XML DSO data island using DTD does not display correct date format
Background : with XML data islands you can bind data to HTML tags. If you do not provide a DTD it will display the information as is. If you provide a DTD IE will display the data according to its datatype. The most significant is dates, by providing the date in the proper XML format IE will display the date in a nice readable format. But being in Ausrtralia I am expecting my date format to be displayed like so : dd/mm/yy It is displaying the dates in American format : mm/dd/yy My regional settings are set to Australian, so why are the dates still displaying in the wrong format ? ...

CRM 4.0 Advanced Find
Hi All, I'm having some trouble upgrading some functionality used in CRM 3.0 to CRM 4.0 Basically the model is.. a contact has a group of interests these interests exist in a seperate entity the contact is connected to an interest through a link entity (contact- interest). (basically making a many to many) The user can then use an advanced find to search for all contacts with a certain set of interests. For example: Contact 1 has interest A and interest B Contact 2 has interest A The user wants to find contacts with interest A and interest B An advanced find with contacts with conta...

validating XML with XmlValidatingReader
I have a doc that that I am entering an incorrect value in a node that expects an restricted enumeration yet I can't get the ValidationEventHandler to fire. Shouldn't it fire if it finds an enumeration that's not listed in the schema? I've also misspelled node tags and it still won't fire. Am I missing something? Thanks. Public Shared Function IsValid(ByVal cXML As String) As Boolean _valid = True Dim schemaColl As XmlSchemaCollection schemaColl = New XmlSchemaCollection schemaColl.Add(Nothing, New XmlTextReader("..\myXSD.xsd")) Dim ioStream As Stream i...

Find the first and last occurance of a report printed. #2
Hello, I have a wookbook that contains about 180,000 rows of data across 3 spreadsheets. The data is in Column A and Column B. In Column A I have Mainframe Report Number's and in Column B I have the dates the reports have printed. Column A repeats the report number for each date the report has printed as shown below. COLUMN A COLUMN B AA000001 6/23/06 AA000001 5/10/06 AA000001 10/02/05 AA000002 6/5/06 AA000002 5/10/06 AA000002 4/09/05 AA000002 3/12/04 AA000002 2/14/03 Is it possible to have a macro go thr...

disinclude from xml serialization
How to mark a public member of a class so that it is not included in an xml serialization or deserialization ? Thanks. On 5/5/2010 2:59 PM, John Grandy wrote: > How to mark a public member of a class so that it is not included in an xml > serialization or deserialization ? Thanks. > > Mark the property with the attribute XmlIgnore as below: [XmlIgnore()] public string NotNecessaryString {get; set;} -- Mike ...

Where can I find the dagger footnote mark?
Where can I find the dagger footnote mark? Insert | Symbol With Times New Roman its 134 (or Alt+0134 if you want to do it manually without Insert | Symbol)...for other fonts you'll hve to look and see if the dagger is available. -- ~~~~~~~~~~~~~~~~~~ Rob Giordano Microsoft MVP Expression "Mark P Evans" <Mark P Evans@discussions.microsoft.com> wrote in message news:A9E5F9F7-99FB-4AB6-8BAE-CD69C9746A52@microsoft.com... | Where can I find the dagger footnote mark? Rob Giordano (Crash) wrote: > Insert | Symbol > > With Times New Roman its 134 (or Alt+0...

XSLT for viewing XML as Tree
I have some XML I want to display in a section of a web page. I want the XML displayed as a tree. The way you see XML if you load the file in the browser. It shows the tree and you can expand/collapse nodes etc. Is their a way to get the actual transform that does this? I think I remember some people extracted the xslt from some MS IE dll or something like that. http://www.cranesoftwrights.com/resources/showtree/index.htm http://www.codeproject.com/soap/treefromxmlusingxslt.asp Chuck P wrote: > I have some XML I want to display in a section of a web page. > I want the XML displ...

need template on mortgage loan with extra paymts where can i find
i need a mortgage loan with extra payments template to download, where can I find one online???? ...

XML Serialization
I'm not sure if this is the appropriate group for this post or not. Please advise if it is not. I have an xml structure similar to the following: <xml> <object1> <id/> <name/> </object1> <object2> <id> <name> </object2> <object3> <id/> <name/> </object3> </xml> I created a schema from this where only 1 of the 3 objects can exist using xs:choice. From this schema, I used the xsd utility to create my xml serializable class. My question is this. Each object (1 - 3) needs to be loaded base...

Where can I find a VAT book keeping template?
Help! I want to do my VAT for the year in excel but I cant be bothered to make a template. Any Ideas where I can get one, checked templates online but couldnt see any suitable! ...

xml Templates
Does anyone where i can find or download more reciept templates?.. or maybe a prgram that nmakes it easy to design a template. thanks Pete There are some additional template available on the Reports Library section of Customer Source. I'm not aware of any receipt generator type programs, but XMLSpy from Altova is a terrific XML Editor. -- -- Glenn Adams Tiber Creek Consulting http://www.tibercreek.com glenn@tibercreek.com ---------------------------------------------- Please DO NOT respond to me directly but post all responses here in the newsgroup so that all can share the informa...

xml data in excel
I have designed an excel template with tabular format (row by row input) for user input. I have to make the validation for those input. My question is that is it possible to use XML schema as the input format template and use it for the data validation like normal XML validation. Could anyone suggest me how to do that?? Million thanks. ...

Can XML describe different hierarchical data?
I want an XML file to describe hierarchical data where each node is different. Each node will contain different and varied other nodes. Describing this in an XML file would be easy but I'm having a problem with this as related to DTD or XSD. What the XSD really needs to do is describe a node, which can contain other nodes. It could not describe the hierarchy of all the nodes in the XML file. Is it possible to describe a free-form hierarchy in an XSD file? Thanks for your help. Bruce W.1 wrote: > What the XSD really needs to do is describe a node, which can contain > other nod...

Find Available Times
I'm trying to limit resource availability to true work hours of 6 AM to 5 PM, while also having Services that span 1+ days. Is Scheduling Engine functionality capable of Finding Available Times for Resources that do not have consecutive availability of more than 12 hours? What happens now is that if I don't have resource availability of All Day, the Scheduling Engine returns a result of "No results found. Try choosing..." ...

Cannot Start Outlook. Invalid XML
When I try to bring up Outlook it has just begun giving me the following error message "Cannot start Microsoft Outlook. Invalid XML, the view cannot be load." I have attempted to start from RUN using "outlook.exe/navepaneres" with no success. Any other ideas? Instead try; Start-> Run; outlook.exe /resetnavpane (note the space in the command and the spelling of the switch) -- Robert Sparnaaij [MVP-Outlook] Coauthor, Configuring Microsoft Outlook 2003 http://www.howto-outlook.com/ Outlook FAQ, HowTo, Downloads, Add-Ins and more http://www.msou...

How to MoveFirst, MoveNext, MovePrevious, MoveLast in LinQ To XMl Please Help #2
I have the Next XML var xml = new XElement( "clients", new XElement("client", new XAttribute("id",1), new XElement( "name", "Luis"), new XElement( "country", "Portugal") ), new XElement("client", new XAttribute("id",2), n...