Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

get XML element name

Status
Not open for further replies.

zitvig

Technical User
Apr 3, 2002
6
MT
Hi all,

I'm working with some XML files using perl-5.8.7 and p5-XML-XPath-1.13 on FreeBSD6.

How do I get the name of an XML element using XPath? I know the position of where this element would be. In the example below I need a function that returns the string "mystery_tag", knowing that this would be the first child of /root/data/details/

Code:
<root>
	<info>some text</info>
	<more_info></more_info>
	<data>
		<details>
			[!]<mystery_tag>[/!]
				<a>some</a>
				<b>text</b>
				<c>here</c>
			</mystery_tag>
			<stuff></stuff>
		</details>
	</data>
</root>

My knowledge of perl is quite limited so any links with examples using XPath would be appreciated.

thanks
 
Have you considered any of the excellent XML parsers over at
Sorry dunno the 1st thing about XPath, but always go to cpan when I'm looking for something like that

HTH
--Paul

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
I'm with Paul, I don't know much about XPath - I did give it a shot with some results that could be helpful. Did you look at the docs for XPath? This is pretty much straight out of the documentation:
Code:
use XML::XPath;
use XML::XPath::XMLParser;

my $xp = XML::XPath->new(filename => 'test.txt');
my $nodeset = $xp->find('/root/data/details'); # find all nodes under details

foreach my $node ($nodeset->get_nodelist) {
    print "FOUND\n\n", 
        XML::XPath::XMLParser::as_string($node),
        "\n\n";
}
Which prints:
Code:
FOUND

<details>
            <mystery_tag>
                <a>some</a>
                <b>text</b>
                <c>here</c>
            </mystery_tag>
            <stuff />
        </details>
So you could split the results of XML::XPath::XMLParser::as_string($node) into an array and look at the second element in that array to find the name of your mystery tag.

What are you doing with the XML info once it's parsed? Is there a particular reason you're using XML::XPath as opposed to another parser?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top