最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

xml - How to fetch the child node with given criteria in javascript DOM api? - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question asked Aug 20, 2012 at 5:18 mkomko 22.1k50 gold badges135 silver badges195 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

In 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.

发布评论

评论列表(0)

  1. 暂无评论