我该如何阅读这个XML?

时间:2014-01-22 13:33:24

标签: jquery xml

我从另一个使用label属性的XML中调整了这个值:

我的JQuery / HTML

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<script>
$(document).ready(function() {
    var myArr = [];

    $.ajax({
        type: "GET",
        url: "_vti_bin/ListData.svc/InternalPhoneList", // change to full path of file on server
        dataType: "xml",
        success: parseXml,
        complete: setupAC,
        failure: function(data) {
            alert("XML File could not be found");
            }
    });

    function parseXml(xml)
    {
        //find every query value
        $(xml).find("FistName").each(function()
        {
            myArr.push($(this).attr("label"));
        }); 
    }

    function setupAC() {
        $("input#searchBox").autocomplete({
                source: myArr,
                minLength: 1,
                select: function(event, ui) {
                    $("input#searchBox").val(ui.item.value);
                    $("#searchForm").submit();
                }
        });
    }
});

<h1>jQuery Autocomplete using XML as Data Source Example</h1>
<label for="searchBox">Keyword Search</label>
<input type="text" id="searchBox" name="searchString" />

<button name="searchKeyword" id="searchKeyword">Sumbit</button>

我认为这是我需要改变的地方:

myArr.push($(this).attr("label"));

XML Extract:

<m:properties>
    <d:ContentTypeID>0x0100ABE14F110F6A3344B2BA46A9B5BE8CDD</d:ContentTypeID>
    <d:Title>test</d:Title>
    <d:FirstName>John</d:FirstName>
    <d:LastName>Smith</d:LastName>
    <d:Extension>3928</d:Extension>
    <d:Department>Financial Services</d:Department>
    <d:Location>UK</d:Location>
    <d:TryExtension m:null="true" />
    <d:JobTitle m:null="true" />
    <d:Nee m:null="true" />
    <d:MobilePhone m:null="true" />
    <d:Fax m:null="true" />
    <d:Notes m:null="true" />
    <d:ContactNumber m:null="true" />
    <d:Id m:type="Edm.Int32">2</d:Id>
    <d:ContentType>Item</d:ContentType>
    <d:Modified m:type="Edm.DateTime">2014-01-22T11:39:26</d:Modified>
    <d:Created m:type="Edm.DateTime">2014-01-21T17:10:53</d:Created>
    <d:CreatedById m:type="Edm.Int32">15</d:CreatedById>
    <d:ModifiedById m:type="Edm.Int32">19</d:ModifiedById>
    <d:Owshiddenversion m:type="Edm.Int32">2</d:Owshiddenversion>
    <d:Version>1.0</d:Version>
    <d:Path>/sites/230080/CP/Switchboard/Lists/Internal Phone List</d:Path>
  </m:properties>

要点:

我想提取名字

  <d:FirstName>John</d:FirstName>

1 个答案:

答案 0 :(得分:1)

首先,XML不包含标记<FirstName>,它是<d:FirstName>。如果您想要节点的文本值,可以使用text()

由于您的标记名称在jQuery中包含保留的:伪元素选择器,因此您需要使用\\:转义它:

//find every query 
$(xml).find('d\\:FirstName').each(function() {
    myArr.push($(this).text());
}); 

jsFiddle Demo