jQuery XML parsing with namespaces

2018-12-31 09:39发布

I'm new to jQuery and would like to parse an xml document.

I'm able to parse regular XML with the default namespaces but with xml such as:

<xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
   <s:Schema id="RowsetSchema">
     <s:ElementType name="row" content="eltOnly" rs:CommandTimeout="30">
       <s:AttributeType name="ows_ID" rs:name="ID" rs:number="1">
        <s:datatype dt:type="i4" dt:maxLength="4" />
      </s:AttributeType>
       <s:AttributeType name="ows_DocIcon" rs:name="Type" rs:number="2">
        <s:datatype dt:type="string" dt:maxLength="512" />
      </s:AttributeType>
       <s:AttributeType name="ows_LinkTitle" rs:name="Title" rs:number="3">
        <s:datatype dt:type="string" dt:maxLength="512" />
      </s:AttributeType>
       <s:AttributeType name="ows_ServiceCategory" rs:name="Service Category" rs:number="4">
        <s:datatype dt:type="string" dt:maxLength="512" />
      </s:AttributeType>
    </s:ElementType>
  </s:Schema>
   <rs:data>
    <z:row ows_ID="2" ows_LinkTitle="Sample Data 1" />
    <z:row ows_ID="3" ows_LinkTitle="Sample Data 2" />
    <z:row ows_ID="4" ows_LinkTitle="Sample Data 3" />
  </rs:data>
</xml>

All I really want are the <z:row>'s.

So far, I've been doing:

$.get(xmlPath, {}, function(xml) {
    $("rs:data", xml).find("z:row").each(function(i) {
        alert("found zrow");
    });
}, "xml");

With really no luck. Any ideas? Thanks.

20条回答
深知你不懂我心
2楼-- · 2018-12-31 10:01

just replaced the namespace by empty string. Works fine for me. Tested solution across browsers: Firefox, IE, Chrome

My task was to read and parse an EXCEL-file via Sharepoint EXCEL REST API. The XML-response contains tags with "x:" namespace.

I decided to replace the namespace in the XML by an empty string. Works this way: 1. Get the node of interest out of the XML-response 2. Convert the selected node XML-Response (Document) to String 2. Replace namespace by empty string 3. Convert string back to XML-Document

See code outline here -->

function processXMLResponse)(xData)
{
  var xml = TOOLS.convertXMLToString("", "",$(xData).find("entry content")[0]);
  xml = xml.replace(/x:/g, "");            // replace all occurences of namespace
  xData =  TOOLS.createXMLDocument(xml);   // convert string back to XML
}

For XML-to-String conversion find a solution here: http://www.sencha.com/forum/showthread.php?34553-Convert-DOM-XML-Document-to-string

查看更多
刘海飞了
3楼-- · 2018-12-31 10:03

I got it.

Turns out that it requires \\ to escape the colon.

$.get(xmlPath, {}, function(xml) {
    $("rs\\:data", xml).find("z\\:row").each(function(i) {
        alert("found zrow");
    });
}, "xml");

As Rich pointed out:

The better solution does not require escaping and works on all "modern" browsers:

.find("[nodeName=z:row]")
查看更多
登录 后发表回答