f



looping through names of nodes and sub nodes

I am trying to transform my XML to produce just a tree of the unique
nodes and subnodes and am having no luck.

this is the sample xml

<MyRoot>
 <contact>
    <name>Jane Doe</name>
    <country>USA</country>
 </contact>
 <magazines>
     <magazine>
       <magazine_name>Some Magazine</magazine_name>
       <year>2004</year>
    </magazine>
     <magazine>
       <magazine_name>Some Magazine</magazine_name>
       <year>2004</year>
    </magazine>
</magazines>
</MyRoot>

Desired Text Result from transformation
Group: MyRoot
  Group:contact
        name
        country
  End_Group:contact
  Group:magazines
      Group: magazine
          magazine_name
          year
  End_Group:magazines
End_Group:MyRoot

I am getting lost in the looping of it as far as starting and ending
the group notation.

Pointers and suggestions welcome
K

0
9/20/2005 1:48:16 PM
comp.text.xml 8781 articles. 0 followers. Post Follow

5 Replies
478 Views

Similar Articles

[PageSpeed] 24

Hi,

Tempore 15:48:16, die Tuesday 20 September 2005 AD, hinc in foro {comp.text.xml} scripsit <k.a.bouton@reading.ac.uk>:

> <MyRoot>
>  <contact>
>     <name>Jane Doe</name>
>     <country>USA</country>
>  </contact>
>  <magazines>
>      <magazine>
>        <magazine_name>Some Magazine</magazine_name>
>        <year>2004</year>
>     </magazine>
>      <magazine>
>        <magazine_name>Some Magazine</magazine_name>
>        <year>2004</year>
>     </magazine>
> </magazines>
> </MyRoot>
>
> Desired Text Result from transformation
> Group: MyRoot
>   Group:contact
>         name
>         country
>   End_Group:contact
>   Group:magazines
>       Group: magazine
>           magazine_name
>           year
>   End_Group:magazines
> End_Group:MyRoot

Try:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:key name="element" match="*" use="name()"/>

<xsl:template match="*">
<xsl:if test="generate-id()=generate-id(key('element',name())[1])">
	<xsl:for-each select="ancestor::*">
		<xsl:text>	</xsl:text>
	</xsl:for-each>
	<xsl:if test="not(*)">
		<xsl:value-of select="name()"/>
		<xsl:text>&#10;</xsl:text>
	</xsl:if>
	<xsl:if test="*">
		<xsl:text/>Group: <xsl:value-of select="name()"/>
		<xsl:text>&#10;</xsl:text>
		<xsl:apply-templates select="*"/>
		<xsl:for-each select="ancestor::*">
			<xsl:text>	</xsl:text>
		</xsl:for-each>
		<xsl:text/>End_Group: <xsl:value-of select="name()"/>
		<xsl:text>&#10;</xsl:text>
	</xsl:if>
</xsl:if>
</xsl:template>

</xsl:stylesheet>

This might become rather tough when the real structure contains identically named nodes in another context.

regards,
-- 
Joris Gillis (http://users.telenet.be/root-jg/me.html)
Don't send spam. I don't like it and it is illegal.
0
roac (340)
9/20/2005 2:07:44 PM
that seems to work prefect.Thanks. it was the generate_id where I got
lost. thanks again
K

0
9/20/2005 2:54:34 PM
OK - now I'd like to get fancy...
Is there anyway, if there are nodes which are repeated to indicate it?
eg
if if node names has multiple name under it
<magazines>
  <magazine>some mag</magazine>
  <magazine>another mag</magazine>
</magazines>

to print out
+   Group: magazines
Thanks
K

0
9/22/2005 3:37:44 PM
Hi,

Tempore 17:37:44, die Thursday 22 September 2005 AD, hinc in foro {comp.text.xml} scripsit bouton <k.a.bouton@reading.ac.uk>:

> Is there anyway, if there are nodes which are repeated to indicate it?
> eg
> if if node names has multiple name under it
> <magazines>
>   <magazine>some mag</magazine>
>   <magazine>another mag</magazine>
> </magazines>

Try adding:
<xsl:if test="count(../*[name()=name(current())]) &gt; 1">+</xsl:if>

like in this stylesheet:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:key name="element" match="*" use="name()"/>

<xsl:template match="*">
<xsl:if test="generate-id()=generate-id(key('element',name())[1])">
<xsl:variable name="indent">
	<xsl:for-each select="ancestor::*">
	<xsl:text> </xsl:text>
	</xsl:for-each>
</xsl:variable>
<xsl:value-of select="$indent"/>
<xsl:if test="count(../*[name()=name(current())]) &gt; 1">+</xsl:if>
<xsl:if test="not(*)">
<xsl:value-of select="name()"/>
<xsl:text>&#10;</xsl:text>
</xsl:if>
<xsl:if test="*">
<xsl:text/>Group: <xsl:value-of select="name()"/>
<xsl:text>&#10;</xsl:text>
<xsl:apply-templates select="*"/>
<xsl:value-of select="$indent"/>
<xsl:text/>End_Group: <xsl:value-of select="name()"/>
<xsl:text>&#10;</xsl:text>
</xsl:if>
</xsl:if>
</xsl:template>

</xsl:stylesheet>

regards,
-- 
Joris Gillis (http://users.telenet.be/root-jg/me.html)
«Error, keyboard not found— press F1 to continue» , BIOS
0
roac (340)
9/22/2005 3:46:28 PM
perfect- thanks
K

0
9/22/2005 4:02:43 PM
Reply:

Similar Artilces:

XSLT Select nodes without text-node children whose names starts with specifix text
Question on XSL expression Got this XML: <Body> <Page> <Line no="9" detail="true"> <onefield>onefieldstext</onefield> <twofield>twofieldstext</twofield> </Line> <Line no="10" detail="true"> <onefield>onefieldstext</onefield> <fgman9>fgmanfieldstext</fgman9> <twofield>twofieldstext</twofield> </Line> <Line no="11" detail="true"> <onefield>onefieldstext</onefield> <twofield>twofieldste...

XML Node, HTML Node
hi guys, how can distinguish between XML Node and HTML Node, using attributes or method .. thanks . alhalayqa wrote: > how can distinguish between XML Node and HTML Node, using attributes or > method .. In the XML DOM nodes do not have an id property or a className property while in the HTML DOM nodes do have those properties. On the other hand there are specializations of the XML DOM like the SVG DOM where id or className are properties too. Thus if you parse XML with namespaces with browsers like Mozilla or Opera the parser recognizes namespaces like the XHTML 1 namespace o...

Why treat text nodes as nodes?
One of the things I find most unnatural about most XML APIs is that they try to abstract both elements and text into some kind of "node" object when they have virtually nothing in common. The reason these APIs do it is to make it possible for both text and elements to be children of elements. But there is another way. The XPath/XQuery data model does not allow two consecutive text nodes. As far as I can tell, most XML processing software automatically merges consecutive text nodes. This means that the number of text segments directly under an element is bound by the number of sub-e...

xsl variable $node/text() but $node can non-node-set help!
I have a variable $value as a parameter in the following template: <xsl:template name="myTemplate"> <xsl:param name="value"/> <xsl:if test="$value"> <xsl:value-of select="$value"/> </xsl:if> </xsl:template> Now i call myTemplate sometimes whit the a parameter $value that is sometimes a text node, and sometimes it is not even a node. Example: <inputDoc> <a>hello</a> <a/> </inputDoc> xsl: <xsl:for-each select="/inputDoc/a"> <xsl:call-template name="myT...

need a help to create XML node with text and sub child.
Hi folks I need a help to create XML node with text and sub child. -------------------------------------------------------- I want to create "ADDR" node with text and child node. (First child node and then text.) <?xml version="1.0" encoding="UTF-8" ?> - <ROOT> - <NODE> <child-1 attr="attr-value">This is child text</child-1> - <ADDR> <postcode>12345</postcode> Address information </ADDR> </NODE> </ROOT> -------------------------------------------------------- I can crea...

Reality check: Is it sensible to link XML nodes to other XML nodes in the same file?
I've got a whole list of descriptions of stages in a production process, which are organised as a sequence of steps, with some branching (i.e. a sort of flow chart)... and thought I'd try and get with the times and model the data using XML! I'm hoping I'll eventually be able to display each 'step' (node) on it's own Web page, and show what link comes next. Is this a sensible thing to attempt to do? If so, how do I link to other nodes in the XML file? Should the <link> be to another node's <id>? And will each node need a 'friendly' <name...

php xml DOM/xpath how to reference child nodes by name within foreach loop?
I am having trouble extracting information from this xml document in php. The methods I=92ve seen for printing the elements under each <server> do it blindly, looking only to see if it=92s a child of <server>. What I would like to do is reference each element by name, but am not sure how=85 Any suggestions? <?php $xmlDOM =3D new DOMDocument(); $xmlDOM->load("servers.xml"); $SERVERS =3D $xmlDOM->getElementsByTagName("server"); foreach ($SERVERS AS $svr) { ##### Print elements of <server> HERE ##### ##### ##### #...

Text nodes and element nodes query
Hi all, The code below gets me a list of all the nodes within the node object called xml_tags_root. NodeList nl = xml_tags_root.getChildNodes(); The length of nodelist I get is double the number of actual elements! This is because after every element node there is text node which is (I think) the whitespace in the XML document. Is there a way to get only the element nodes? Please advice. thanks, ASD Hi, Look at getElementsByTagName(....) Regards, Arnaud "asd" <arvindsd@yahoo.com> a �crit dans le message news: 1116833345.887839.95270@g47g2000cwa.googlegroups.com... &...

Removing all text nodes from a given node
I've written a method that is supposed to remove all text nodes from a given node and also from its child nodes. The given node is, for example, created from following XML: -------------- <?xml version="1.0" encoding="utf-8" ?> <L1>L1 Text <L2>L2 Text <L3>L3 Text</L3> </L2> <L2_1>L2_1 Text</L2_1> <L2_2>L2_2 Text</L2_2> </L1> -------------- The method I've written is : -------------- public static void removeEmptyText(org.w3c.dom.Node n) { org.w3c.dom.NodeList nodeList = n.getChildNodes(); for (int...

XML DOM: XML/XHTML inside a text node
In my program, I get input from the user and insert it into an XHTML document. Sometimes, this input will contain XHTML, but since I'm inserting it as a text node, xml.dom.minidom escapes the angle brackets ('<' becomes '&lt;', '>' becomes '&gt;'). I want to be able to override this behavior cleanly. I know I could pipe the input through a SAX parser and create nodes to insert into the tree, but that seems kind of messy. Is there a better way? Thanks. On Thu, 2 Nov 2005 noahlt@gmail.com wrote: > In my program, I get input from the us...

XML text node
Hi!In my application, I want to use XML files as configuration files.I made a VI using XML DOM Parser fonctions to fill the text nodes with the desired information. In the case I want to overwrite previous information stored in a node , the data has to be written as text and is placed between the corresponding markers (for exemple in the attached file &lt;InputValue&gt;data&lt;\InputValue&gt;).However if a node is empty (no text previoulsy written), the marker becomes &lt;InputValue/&gt;. In that case, it is impossible to write data in it... Why is that ?I think my code...

How to find non-existing nodes or nodes with no text
Ok, this must be simple but the more i search the more i don't find. It's about SimpleXML and PHP. How to find non-existing nodes or nodes with no text My XML file looks a little bit like this: i.e. 1 <discography> <CD> <title></title> <year>1978</year> </CD> </discography> i.e. 2: <discography> <CD> <year>1978</year> </CD> </discography> In i.e. 1, the tag <title> is empty. How do i test for empty tags in PHP? In i.e. 2, the tag <title> doesn't even exist. How do i ...

How to find non-existing nodes or nodes with no text.
Ok, this must be simple but the more i search the more i don't find. It's about SimpleXML and PHP. How to find non-existing nodes or nodes with no text My XML file looks a little bit like this: i.e. 1 <discography> <CD> <title></title> <year>1978</year> </CD> </discography> i.e. 2: <discography> <CD> <year>1978</year> </CD> </discography> In i.e. 1, the tag <title> is empty. How do i test for empty tags in PHP? In i.e. 2, the tag <title> doesn't even exist. How do i ...

Get XML values from nodes and child nodes
Hi everybody. My XML file is: <Locatore> <NumeroProgressivo>001</NumeroProgressivo> <CodiceFiscale>CSTNDA69P90H523R</CodiceFiscale> <PersoneFisiche> <Cognome>CAST</Cognome> <Nome>NADIR</Nome> <Sesso>F</Sesso> <DataNascita>10091979</DataNascita> <ComuneNascita>RONCA</ComuneNascita> <ProvinciaNascita>BL</ProvinciaNascita> </PersoneFisiche> </Locatore> <Locatore> <NumeroProgressivo>002</NumeroProgressivo> <CodiceFiscale>PRSGRI74L29F443L</CodiceFiscale> <PersoneFisiche> <Cognome>PERISSI</Cognome> <Nome>IGOR</Nome> <Sesso>M</Sesso> <DataNascita>29071970</DataNascita> <ComuneNascita>MONTE</ComuneNascita> <ProvinciaNascita>SA</ProvinciaNascita> </PersoneFisiche> </Locatore> I need to get in ONE RECORD, both node value and his child nodes values, like this 001 | CSTNDA69P90H523R | CAST | NADIR | F | 10091979 | RONCA | BL 002 | PRSGRI74L29F443L | PERISSI | IGOR | M | 29071970 | MONTE | SA ..... With this: SELECT X.valore.query('NumeroProgressivo').value('.', 'VARCHAR(20)') as NumeroProgressivo, X.valore.query('CodiceFiscale').value('.', 'VARCHAR(16)') as CodiceFiscale FROM Tbulk CROSS APPLY Tbulk.nodes('Fornitura/Documento/S...

select nodes with child node A and child node B
I have an XML document that has multiple childe nodes like the one at the end of this message What syntax would I use with selectNodes to select all viewentry nodes that have an entrydata child node with a name attribute equal to "CourseOrMeetingName" that has a text childe node with the text Course ABC AND that also have an entrydata child with a name attribute equal to Start Date that has a datetime child node with the text 20070110 I was trying something like //viewentry[ (entrydata[@name='CourseOrMeetingName'][text='Course ABC']) and (entrydata[@name='St...

Inserting Nodes between Nodes
Hi, XML novice here with another question. I need to add a XML node like, [code] <child01> <child02> <text></text> <image>image 1</image> <image>image 2</image> </child02> </child01> [/code] into this node between the ending </child01> and beginning <child01> of the [code] <child01> <child02> <text></text> <image>image 1</image> <image>image 2</image> <...

How to loop through nodes of xml through xslt
--089e013a0d6eca083d04ff6820db Content-Type: text/plain; charset=UTF-8 Hi, I have two xml files. *File1.xml* *<?xml version="1.0" encoding="UTF-8"?>* *<InfoTag>* *<Procedure attrProc="TestProcA" attrLevel="1">* * <downTime>* * <acceptableDownTime>* * <all/>* * </acceptableDownTime>* * <downTimePeriod time="600000000"/>* * </downTime>* * </Procedure>* * <Procedure attrProc="TestProcB" attrLevel="2"...

selecting nodes between other nodes
Hi! <root> <foo>bar</foor> <blah /> <blah2 /> <a> <b /> <c /> </> </root> I want to select everything between <foo> and <a>. Is this possible? Timo In article <2jbjjhFvf4ttU1@uni-berlin.de>, Timo Nentwig <tcn@spamgourmet.org> wrote: % <root> % <foo>bar</foor> % <blah /> % <blah2 /> % <a> % <b /> % <c /> % </> % </root> % I want to select everything between <foo> and <a>. Is this possible? How about <xsl:styles...

I want to select all the node names beneath a given node
Dear all I have a diffgram: <?xml version="1.0" standalone="yes"?> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <NewDataSet> <PolicyInwards diffgr:id="PolicyInwards1" msdata:rowOrder="0" diffgr:hasChanges="modified"> <PolicyID>POL0001</PolicyID> <InsuredName>Insured Co 111</InsuredName> <InceptDate>2007-01-01T00:00:00+00:00</InceptDate> <BrokerCode>...

extracting xml node name
hi, how can i get the NAME of the XML node, example - SELECT EXTRACT (VALUE (e), '/').getstringval () as xml , EXTRACTVALUE (VALUE (e), '/') as VALUE --, ??? as tag FROM TABLE (XMLSEQUENCE (EXTRACT ( XMLTYPE ('<A> <B>2</B> <C>3</C> <D>4</D> </A>' ), '/A/*'))) e the result should be - (the first & second are ok, but how to get the third ?) - xml --- <B>2</B> <C>3</C> <D>4</D> value ----- 2 3 4 tag --- B C D Thanks, Shay ...

Getting all nodes and node details from xml using xquery
Hi, I haev the following code: DECLARE @x xml SET @x=' <Root> <row id="1"><name>Larry</name><oflw>some text</oflw></row> <row id="2"><name>Joe</name></row> <row id="3" /> </Root> ' exec sp_xml_preparedocument @idoc OUTPUT, @x SELECT * FROM OPENXML(@idoc, '/Root') This gives the following details id parentid nodetype localname prefix namespaceuri datatype pr...

urlsafe_b64decoding of xml node text
Hi All, I am running Apache with mod_python. A post message to my server contains an xml of the form <a> <b>(some base64 ur-safe-encoded data)</b> </a> I use minidom to parse the xml posted, and now try to decode the data using the following import minidom import base64 decData = base64.urlsafe_b64decode(data) #data is the above mentioned url-safe-encoded data This line fails with the following error Error : <type 'exceptions.TypeError'> Error : character mapping must return integer, None or unicode Error : <traceback object at 0x1b38e40> ...

extracting text from an XML node
Hi, suppose i get the simple xml sample: <foo> 1 <bar>2</bar> 3 </foo> Now suppose i want to extract all the text of only the 'foo' node, ie expected result is '1 3'. I tried both <xsl:template match="foo"> <xsl:value-of select="text()" /> </xsl:template> and <xsl:template match="foo"> <xsl:value-of select="." /> </xsl:template> but the former lead to '1' and the latter to '1 2 3' (using xsltproc & firefox). What did i missed ? tha...

XML Document Node Names
Hello. I have a Javascript that gets data from an XML document and displays it through javascript. The problem is that when I do dcfile.getElementsByTagName("subhead")[0].firstChild.nodeName all I get is #text. Can you tell me why? Here is my code: /* The Dante-Cubed Standardized Markup Language Javascript API ---[Powered by DCScript]--- Written by Sean M. Hall, Dante, and Peter-Paul Koch This is the only script we request you ask for permission to use Permission: dcsml@sfhe.cjb.net */ if (location.search.indexOf("=") > 2) { file = location.search.substring(location.se...

Web resources about - looping through names of nodes and sub nodes - comp.text.xml

Looping - Wikipedia, the free encyclopedia
Audio induction loop , an aid for the hard of hearing. They are a loop of cable around a designated area, usually a room or a building, which ...

App Store - Flyloop: Butterfly Looping Fun
Read reviews, get customer ratings, see screenshots, and learn more about Flyloop: Butterfly Looping Fun on the App Store. Download Flyloop: ...

NASA Sees Fiery Looping Rain on the Sun [hd video] - Flickr - Photo Sharing!
Eruptive events on the sun can be wildly different. Some come just with a solar flare, some with an additional ejection of solar material called ...

David Chen - Looping Cello and Piano Music - YouTube
Music using looping cello, performed by David Chen.

Update: King Gizzard's "super heavy" infinite looping new album "has 9 songs and it never ends"
The insanely prolific seven-piece open up about the ambitious concept and sound to their next album.

YouTube - The Smiler is the world's first 14 looping rollercoaster
Veröffentlicht am 09.05.2013 The world record for the most loops in a rollercoaster has been officially smashed by Alton Towers Resort's The ...

Ad of the Day: Honda Just Keeps Driving in This Hypnotic, Looping Ad That Never Ends
What better way for an automaker to communicate performance, longevity and a never-ending commitment to quality than with an ad that itself never ...

Aurora Borealis: Like Spaghetti Looping Toward Earth? - Alaska Dispatch
Through a process called "magnetic reconnection" a University of Iowa professor of physics and astronomy and his team are seeing the aurora borealis ...

GIF Chat launches on Android, offers looping video clips and text messaging
The group messaging app space is full of great choices, but GIF Chat is trying to get in on the craze with its own set of features.

Tiiny’s bite-size, self-destructing photos and looping videos will keep you entertained
Tiiny Share tiny photos & looping videos Slingshot Snapchat Instagram Tiinys bite-size, self-destructing photos and looping videos will keep ...

Resources last updated: 3/6/2016 8:32:32 PM