네임 스페이스를 사용한 jQuery XML 구문 분석
저는 jQuery를 처음 사용하며 xml 문서를 구문 분석하고 싶습니다.
기본 네임 스페이스를 사용하지만 다음과 같은 xml을 사용하여 일반 XML을 구문 분석 할 수 있습니다.
<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>
내가 정말로 원하는 것은 <z:row>
's.
지금까지 저는 다음과 같이했습니다.
$.get(xmlPath, {}, function(xml) {
$("rs:data", xml).find("z:row").each(function(i) {
alert("found zrow");
});
}, "xml");
정말 운이 없습니다. 어떤 아이디어? 감사.
알았어.
\\
콜론을 탈출 해야한다는 것이 밝혀졌습니다 .
$.get(xmlPath, {}, function(xml) {
$("rs\\:data", xml).find("z\\:row").each(function(i) {
alert("found zrow");
});
}, "xml");
Rich는 다음과 같이 지적했습니다.
더 나은 솔루션은 이스케이프가 필요하지 않으며 모든 "최신"브라우저에서 작동합니다.
.find("[nodeName=z:row]")
나는 운이없는 플러그인과 모든 종류의 솔루션에 대해이 독서에 몇 시간을 보냈습니다.
ArnisAndy는이 답변이 제공되는 jQuery 토론에 대한 링크를 게시했으며 이것이 Chrome (v18.0), FireFox (v11.0), IE (v9.08) 및 Safari (v5.1.5)에서 작동하는지 확인할 수 있습니다. ) jQuery (v1.7.2) 사용.
콘텐츠 이름이 <content : encoded> 인 WordPress 피드를 스크랩하려고하는데 이것이 저에게 효과적이었습니다.
content: $this.find("content\\:encoded, encoded").text()
jquery 1.5를 사용하는 경우 노드 선택기 속성 값 주위에 따옴표를 추가해야 작동합니다.
.find('[nodeName="z:row"]')
위의 답변이 정확 해 보이지만 웹킷 브라우저 (Safari, Chrome)에서는 작동하지 않습니다. 더 나은 해결책은 다음과 같습니다.
.find("[nodeName=z:myRow, myRow]")
누군가가 jQuery없이 일반 자바 스크립트를 사용하고 Google 크롬 (웹킷)의 경우이를 수행해야하는 경우 많은 연구와 테스트를 거친 후 이것이 작동하도록하는 유일한 방법입니다.
parentNode.getElementsByTagNameNS("*", "name");
다음 노드를 검색하는 데 작동합니다 <prefix:name>
.. 보시다시피 접두사 또는 네임 스페이스가 생략되었으며 태그 이름이 인 경우 다른 네임 스페이스의 요소와 일치합니다 name
. 그러나 이것이 당신에게 문제가되지 않기를 바랍니다.
이 중 어느 것도 나를 위해 일하지 않았습니다 (Google 크롬 확장 프로그램을 개발 중입니다).
getElementsByTagNameNS("prefix", "name")
getElementsByTagName("prefix:name")
getElementsByTagName("prefix\\:name")
getElementsByTagName("name")
편집 : 잠자기 후 작업 해결 방법을 찾았습니다. :)이 함수는 다음nodeName
과 같이전체와일치하는 첫 번째 노드를 반환합니다<prefix:name>
.
// Helper function for nodes names that include a prefix and a colon, such as "<yt:rating>"
function getElementByNodeName(parentNode, nodeName)
{
var colonIndex = nodeName.indexOf(":");
var tag = nodeName.substr(colonIndex + 1);
var nodes = parentNode.getElementsByTagNameNS("*", tag);
for (var i = 0; i < nodes.length; i++)
{
if (nodes[i].nodeName == nodeName) return nodes[i]
}
return undefined;
}
일치하는 모든 요소를 반환해야하는 경우 쉽게 수정할 수 있습니다. 도움이 되었기를 바랍니다.
위의 솔루션 중 어느 것도 잘 작동하지 않습니다. 나는 이것을 발견하고 속도가 향상되었습니다. 이것을 추가하고 매력처럼 작동했습니다.
$.fn.filterNode = function(name) {
return this.find('*').filter(function() {
return this.nodeName === name;
});
};
용법:
var ineedthatelementwiththepsuedo = $('someparentelement').filterNode('dc:creator');
"\\"이스케이프는 완전하고 간단하지 않습니다.
.find('[nodeName="z:row"]')
Jquery 1.7에서 메소드가 손상된 것 같습니다. 필터 함수를 사용하여 1.7에 대한 솔루션을 찾을 수있었습니다. 여기에서 Javascript XML Node Finding Performance 향상
jQuery 1.7부터 네임 스페이스 요소를 찾기위한 일부 해결 방법에 문제가 있다는 점은 주목할 가치가 있습니다. 자세한 내용은 다음 링크를 참조하십시오.
- .find ( '[nodeName = "z : row"]')를 수행 할 수있는 기능에 대한 브라우저 간 지원이 부족하다는 jQuery 버그 티켓
- 일부 성능 테스트와 함께 제안 된 플러그인 해결 방법입니다.
주석에서 찾은 해결책 : jQuery $ (). find를 사용하여 네임 스페이스로 XML 구문 분석
콜론 뒤에 노드 이름의 두 번째 절반을 사용하면 나를 위해 일했습니다. 중고 .find ( "위도") 대신 .find ( "지리적 \ 위도") 그리고 그것은 나를 위해 일했습니다.
내 설정 :
- 크롬 42
- jQuery 2.1.3
샘플 XML (Google Contacts API의 스 니펫) :
<entry>
<id>http://www.google.com/m8/feeds/contacts/mstefanow%40gmail.com/base/0</id>
<gd:email rel="http://schemas.google.com/g/2005#other" address="email@example.com" primary="true"/>
</entry>
파싱 코드 :
var xmlDoc = $.parseXML( xml );
var $xml = $( xmlDoc );
var $emailNode = $xml.find( "email" );
$("#email").html($emailNode.attr("address"));
Plnkr : http://plnkr.co/edit/l8VzyDq1NHtn5qC9zTjf?p=preview
jQuery 1.7은 다음에서 작동하지 않습니다.
$(xml).find("[nodeName=a:IndexField2]")
내가 크롬, 파이어 폭스, IE에서 작업하게 된 한 가지 해결책은 IE에서 작동하는 선택기와 Chrome에서 작동하는 선택기를 사용하는 것입니다.
$(xml).find('a\\\\:IndexField2, IndexField2')
In IE, this returns nodes using the namespace (Firefox and IE require the namespace), and in Chrome, the selector returns nodes based on the non-namespace selector. I have not tested this in Safari, but it should work because it's working in Chrome.
My solution (because I use a Php proxy) is to replace : namespace by _ ... so no more namespace issues ;-)
Keep it simple !
Original Answer : jQuery XML parsing how to get element attribute
Here is an example for how to successfully get the value in Chrome..
item.description = jQuery(this).find("[nodeName=itunes\\:summary]").eq(0).text();
As of beginning of 2016, for me the following syntax works with jQuery 1.12.0:
- IE 11 (11.0.9600.18204, Update 11.0.28, KB3134815):
.find("z\\:row")
- Firefox 44.0.2:
.find("z\\:row")
- Chrome 44.0.2403.89m:
.find("row")
The syntax .find("[nodeName=z:row]")
doesn't work in any of the browsers mentioned above. I found no way to apply a namespace in Chrome.
Putting it all together, the following syntax works in all of the browsers mentioned above: .find("row,z\\:row")
As mentioned above, there are problems with the above solution with current browsers/versions of jQuery - the suggested plug-in doesn't completely work either because of case issues (nodeName
, as a property, is sometimes in all upper case). So, I wrote the following quick function:
$.findNS = function (o, nodeName)
{
return o.children().filter(function ()
{
if (this.nodeName)
return this.nodeName.toUpperCase() == nodeName.toUpperCase();
else
return false;
});
};
Example usage:
$.findNS($(xml), 'x:row');
content: $this.find("content\\:encoded, encoded").text()
is the perfect solution...
There is a plugin jquery-xmlns for jQuery to work with namespaces in selectors.
I have not seen any documentation on using JQuery to parse XML. JQuery typically uses the Browser dom to browse an HTML document, I don't believe it reads the html itself.
You should probably look at the built in XML handling in JavaScript itself.
http://www.webreference.com/programming/javascript/definitive2/
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
Alternatively, you can use fast-xml-parser in your project, and convert the XML data into JS/JSON object. Then you can use it as object property. It doesn't use JQuery or other libraries but it'll solve your purpose.
var xmlData = '<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>'
var jsObj = parser.parse(xmlData,{attrPrefix:"",ignoreTextNodeAttr: false});
document.write(JSON.stringify(jsObj.xml["rs:data"]["z:row"][0],null,4) + "<br>");
document.write(JSON.stringify(jsObj.xml["rs:data"]["z:row"][1],null,4) + "<br>");
document.write(JSON.stringify(jsObj.xml["rs:data"]["z:row"][2],null,4) + "<br>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/fast-xml-parser/2.9.2/parser.min.js"></script>
You can ignore namespaces while parsing to js/json object. In this case you can directly access as jsObj.xml.data.row
.
for(var i=0; i< jsObj.xml.data.row.length; i++){
console.log(jsObj.xml.data.row[i]);
}
Disclaimer: I've created fast-xml-parser.
For Webkit browsers, you can just leave off the colon. So to find <media:content>
in an RSS feed for example, you can do this:
$(this).find("content");
참고URL : https://stackoverflow.com/questions/853740/jquery-xml-parsing-with-namespaces
'developer tip' 카테고리의 다른 글
JavaScript를 사용한 ASP.NET 포스트 백 (0) | 2020.10.06 |
---|---|
Swift에서 '미확인 식별자 사용' (0) | 2020.10.06 |
휴지통으로 파일 보내기 (0) | 2020.10.06 |
8 비트 임베디드 시스템에서 사용할 수있는 flex / bison에 대한 대안이 있습니까? (0) | 2020.10.06 |
MySQL 날짜 / 시간 값을 System.DateTime으로 변환 할 수 없습니다. (0) | 2020.10.06 |