XML Traversal:查找特定的子节点

时间:2016-04-11 21:27:36

标签: jquery xml

我有以下XML文件 -

<?xml version="1.0" encoding="UTF-8"?>
    <prj:Flow xmlns:prj="url1" xmlns:com="url2" xmlns:ns2="url3" xmlns:con="url4" xmlns:ns0="url5" xmlns:ns1="url6" xmlns:ns3="url7">
    <prj:layout comp="abcd">
      <prj:prop>
         <prj:property name="Hardik" value="5000"/>
         <prj:bond att="1"> New Value/hello/mode </prj:bond>
      </prj:prop>
      <prj:bond att="1"> New Value </prj:bond>
    </prj:layout>
    <prj:layout comp="efgh">
      <prj:prop>
         <prj:property name="Vipul" value="6000"/>
         <prj:bond att="2"> New Value/bye/code </prj:bond>
      </prj:prop>
      <prj:bond att="2"> New Value </prj:bond>
    </prj:layout>
    </prj:Flow>

此处每个<layout>代码都有两个孩子 - <prop> and <bond>。我的要求是只从布局标记中获取<bond>数据(属性和文本),而不是<prop>标记下的数据。我如何仅使用jquery实现此目的?任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用以下表达式返回<prj:bond>的直接子项的所有<prj:layout>元素:

var result = yourXml.find("prj\\:layout").children("prj\\:bond");

快速演示:

&#13;
&#13;
var raw = `<?xml version='1.0' encoding='utf-16'?>
<prj:Flow xmlns:prj='url1' xmlns:com='url2' xmlns:ns2='url3' xmlns:con='url4' xmlns:ns0='url5' xmlns:ns1='url6' xmlns:ns3='url7'>
    <prj:layout comp='abcd'>
        <prj:prop>
            <prj:property name='Hardik' value='5000' />
            <prj:bond att='1'> New Value/hello/mode </prj:bond>
        </prj:prop>
        <prj:bond att='1'> New Value </prj:bond>
    </prj:layout>
    <prj:layout comp='efgh'>
        <prj:prop>
            <prj:property name='Vipul' value='6000' />
            <prj:bond att='2'> New Value/bye/code </prj:bond>
        </prj:prop>
        <prj:bond att='2'> New Value </prj:bond>
    </prj:layout>
</prj:Flow>`;
var xml = $($.parseXML(raw));
var result = xml.find("prj\\:layout").children("prj\\:bond").each(function(){
	$("#result").append($(this).text()).append("<br/>");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="result"></p>
&#13;
&#13;
&#13;