使用jQuery解析XML

时间:2011-07-14 20:06:12

标签: jquery xml parsing

我在使用jquery解析此xml文件时遇到问题:

<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:BOT-Memos:-myXSD-2011-07-13T14-29-57" solutionVersion="1.0.0.27" productVersion="14.0.0.0" PIVersion="1.0.0.0" href="http://sharept03sb1/BOT/BOT%20Memos/Forms/template.xsn"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.3"?>
<my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls" xmlns:ma="http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes" xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields" xmlns:q="http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-07-13T14:29:57" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-US">
    <my:content>
        <my:title>Hello</my:title>
        <my:description><html xmlns="http://www.w3.org/1999/xhtml" xml:space="preserve"><div>How are you?</div></html></my:description>
        <my:memo xsi:nil="true"></my:memo>
        <my:group>

        <pc:Person xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls"><pc:DisplayName>Johnny Doe</pc:DisplayName><pc:AccountId>ADMIN\fakeadminuser</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person></my:group>
        <my:meetingDate></my:meetingDate>
        <my:addAttachments>
            <my:attachments>
                <my:attachment xsi:nil="true"></my:attachment>
            </my:attachments>
        </my:addAttachments>
        <my:upload></my:upload>
    </my:content>
</my:myFields>

我正在尝试阅读my:title节点,但我没有运气。这是我用来解析它的特定行。

$.get('target.xml', function(data){
  alert($(data).find("my:memo").text());
});

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

由于某种原因,jQuery可能无法将数据识别为XML。此外,通常通过显式检查nodeName来更好地选择命名空间标记。试试这个:

$.get('target.xml', function(data) {
    alert($(data).find("[nodeName=my:memo]").text());
}, "xml");

或者:

$.ajax({
    type: "GET",
    url: "target.xml",
    dataType: "xml",
    success: function(data) {
        alert($(data).find("[nodeName=my:memo]").text());
    }
});

答案 1 :(得分:0)

猜猜你需要逃脱冒号:alert($(data).find("my\\:memo").text());

这个讨论很好:jQuery XML parsing with namespaces就可以了

答案 2 :(得分:0)

您正在寻找标记,但标记中包含此标记:my:memo xsi:nil="true"

$.get('target.xml', function(data){
  alert($(data).find("my:memo xsi:nil=\"true\"").text());
});

我相信有更好的方法可以做到这一点。