the xml file is like this:
<products>
<product>
<id>1</id>
<name>pen</name>
</product>
<product>
<id>2</id>
<name>pencil</name>
</product>
</products>
<employees>
<employee>
<name>Jack</name>
<employee>
<employee>
<name>Mark</name>
<employee>
</employees>
Can I only get the <name>
nodes which are the childen of <product>
? Is there well adapted xpath
api in javascript dom?
the xml file is like this:
<products>
<product>
<id>1</id>
<name>pen</name>
</product>
<product>
<id>2</id>
<name>pencil</name>
</product>
</products>
<employees>
<employee>
<name>Jack</name>
<employee>
<employee>
<name>Mark</name>
<employee>
</employees>
Can I only get the <name>
nodes which are the childen of <product>
? Is there well adapted xpath
api in javascript dom?
3 Answers
Reset to default 4In modern browsers you could use querySelector
to traverse the xml-tree. Let's say your xml resides within div#xmlsample
, then this code will give you a nodeList for //product/name
in prodNames
:
var xmlDoc = (new DOMParser())
.parseFromString(document.querySelector('#xmlsample').innerHTML,
"application/xml"),
prodNames = xmlDoc.querySelectorAll('product name');
See this jsfiddle
jQuery has an api for parsing and traversing xml.
var xmlObj = $.parseXML(xmlObj);
var nameNodes = xmlObj.find('product > name');
From the doc..
jQuery.parseXML uses the native parsing function of the browser to create a valid XML Document. This document can then be passed to jQuery to create a typical jQuery object that can be traversed and manipulated.
Can I only get the
<name>
nodes which are the childen of<product>
?
The provided XML isn't a well-formed XML document (a single top element is required).
Also, two <employee>
start tags don't have corresponding closing </employee>
end-tags.
If the correct XML document is this:
<pany>
<products>
<product>
<id>1</id>
<name>pen</name>
</product>
<product>
<id>2</id>
<name>pencil</name>
</product>
</products>
<employees>
<employee>
<name>Jack</name>
</employee>
<employee>
<name>Mark</name>
</employee>
</employees>
</pany>
and an XPath expression is really required, then one XPath expression that selects the wanted elements is:
/*/products/product/name
This selects any name
element that is a child of any product
element that is a child of any products
element that is a child of the top element of the XML document.