我有一个从jQuery读取XML的问题。我可以加载xml,但我无法读取它的标签,我想首先阅读“menuitem”,然后读取它的属性,我的代码:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
cache: false,
url: baseUrl + "/sitefinity/services/tafesa/TAFEpagedata.svc/Mainmenu",
data: {},
dataType: 'xml',
success: function (data, textStatus, jqXHR) {
console.log(data);
$(data).find('menuitem').each(function () {
htmlString = htmlString + writeToplevelNav($(this).attr('title'), $(this).attr('url'),$(this));
});
这是我的XML:
<GetMainNavResponse xmlns="http://tempuri.org/">
<GetMainNavResult>
<mainMenu>
<mainitem title="Courses" url="~/courses">
<subitem title="Primary Industries @amp; Science" url="~/courses/primary-ind-science">
<item title="Agriculture" url="~/courses/primary-ind-science/agriculture"/>
<item title="Animal Care @amp; Veterinary Nursing" url="~/courses/primary-ind-science/animal-care-veterinary-nursing"/>
<item title="Aquaculture" url="~/courses/primary-ind-science/aquaculture"/>
<item title="Conservation @amp; Land Management" url="~/courses/primary-ind-science/conservation-land-management"/>
<item title="Horticulture" url="~/courses/primary-ind-science/horticulture"/>
<item title="Science" url="~/courses/primary-ind-science/laboratory-technology"/>
</subitem>
</mainitem>
</mainMenu>
</GetMainNavResult>
</GetMainNavResponse>
任何人都可以帮助我,非常感谢!
答案 0 :(得分:0)
问题是,如果您将代码更改为:
,则您发布的xml中没有名为menuitem的元素$(data).find('mainitem')
您将获得第一个标题为Courses和url~ / courses
的元素随后对于mainMenu主题,我认为你也希望通过以下方式获得它的子项目:
$(data).find('mainitem').each(function () {
$(this).find('subitem').each(function() {
// Do some processing with subitem
});
// Do some processing with mainitem as well
});
然后是子项目:
$(data).find('mainitem').each(function () {
$(this).find('subitem').each(function () {
$(this).find('item').each(function () {
// Process subitem's items
});
// Do some processing with subitem as well
});
// Do some processing with mainitem as well
});
我在这里创建了一个github项目,其中包含一个显示此技术的解决方案: https://github.com/davethomas11/stackoverflow_Q_39502601