我在我的项目中使用Jquery。我有以下xml响应:
<?xml version="1.0" encoding="UTF-8"?>
<details>
<company>
<company-name>abc</company-name>
<employee>
<employee-name>John</employee-name>
</employee>
<employee>
<employee-name>Steve</employee-name>
</employee>
</company>
<company>
<company-name>xyz</company-name>
<employee>
<employee-name>Robert</employee-name>
</employee>
<employee>
<employee-name>Stephen</employee-name>
</employee>
</company>
</details>
现在,我想检索<company>
为<company-name>
的{{1}}的信息,包括其下的所有子雇员(xyz
)。我认为我必须使用<employee>
。有人可以帮我吗?
答案 0 :(得分:1)
您需要结合使用$.parseXML
和.find()
方法。
要根据文本查找特定的节点,可以使用jQuery :contains()
选择器
const data = `<?xml version="1.0" encoding="UTF-8"?><details><company><company-name>abc</company-name><employee><employee-name>John</employee-name></employee><employee><employee-name>Steve</employee-name></employee></company><company><company-name>xyz</company-name><employee><employee-name>Robert</employee-name></employee><employee><employee-name>Stephen</employee-name></employee></company></details>`;
let company = $($.parseXML(data)).find('company-name:contains(xyz)').parent();
console.log('Company: ' + company.find('company-name').text());
company.find('employee').each(function() {
console.log('Employee: ' + $(this).find('employee-name').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 1 :(得分:1)
您可以执行以下操作:
var exampleString = "xyz"
var employees = $(XMLdata).find("company-name:contains(" + exampleString + ")").nextAll("employee");
$.each(employees, function() {
console.log($(this).find("employee-name").text())
});
在下面的演示中查看工作示例:
var XMLdata = $.parseXML('<?xml version="1.0" encoding="UTF-8"?><details> <company> <company-name>abc</company-name> <employee> <employee-name>John</employee-name> </employee> <employee> <employee-name>Steve</employee-name> </employee> </company> <company> <company-name>xyz</company-name> <employee> <employee-name>Robert</employee-name> </employee> <employee> <employee-name>Stephen</employee-name> </employee> </company></details>');
var exampleString = "xyz"
var employees = $(XMLdata).find("company-name:contains(" + exampleString + ")").nextAll("employee");
$.each(employees, function() {
console.log($(this).find("employee-name").text())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>