更改XML标记的属性

时间:2018-03-25 10:54:54

标签: javascript jquery xml parsing xml-parsing

我在重命名xml文件中的tag属性时遇到了问题。 假设我有一个xml,如:

<? xml version = "1.0" encoding = "UTF-8" ?>
<Category name="" count = 4>
    <value id=0>Ali</value>
    <value id=1>Adnan</value>
    <value id=2>Yousaf</value>
    <value id=3>Ahmad</value>
</Category>
<Category name="" count = 5>
    <value id=0>America</value>
    <value id=1>China</value>
    <value id=2>Pakistan</value>
    <value id=3>Canada</value>
    <value id=4>India</value>
</Category>

现在我想在Jquery中更新xml的名称。无论如何要做到这一点。我想要这种类型的实现:

xmlDoc = $.parseXML(xml),
    $xml = $(xmlDoc);
    $($xml).each(function () {
        alert($(this).find("Category[name]").setValue("ABC"));
    });

感谢。

2 个答案:

答案 0 :(得分:0)

我想这是你的答案。

XML Validator

var xml = '<?xml version = "1.0" encoding = "UTF-8" ?> <Categories>     <Category name="" count ="4">       <value id="0">Ali</value>       <value id="1">Adnan</value>         <value id="2">Yousaf</value>        <value id="3">Ahmad</value>     </Category>     <Category name="" count ="5">       <value id="0">America</value>       <value id="1">China</value>         <value id="2">Pakistan</value>      <value id="3">Canada</value>        <value id="4">India</value>     </Category> </Categories>'

xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
$xml.context.children[0].children[0].setAttribute("name","ali")

答案 1 :(得分:0)

将您的XML更新为只有一个root,并且还将id属性更新为id="0",而不是id=0,如下所示。

<?xml version="1.0" encoding="utf-8"?>
  <Categories>
    <Category name="" count ="4">
      <value id="0">Ali</value>
      <value id="1">Adnan</value>
      <value id="2">Yousaf</value>
      <value id="3">Ahmad</value>
    </Category>
    <Category name="" count ="5">
      <value id="0">America</value>
      <value id="1">China</value>
      <value id="2">Pakistan</value>
      <value id="3">Canada</value>
      <value id="4">India</value>
    </Category>
  </Categories>

以下JQuery将更新XML中的所有name属性

&#13;
&#13;
$(document).ready(function() {
  var str = '<?xml version="1.0" encoding="utf-8"?><Categories><Category name="" count ="4"><value id="0">Ali</value><value id="1">Adnan</value><value id="2">Yousaf</value><value id="3">Ahmad</value></Category><Category name="" count ="5"><value id="0">America</value><value id="1">China</value><value id="2">Pakistan</value><value id="3">Canada</value><value id="4">India</value></Category></Categories>';
  var xmlDoc = $.parseXML(str);
  var xmlData = $(xmlDoc);
  $(xmlData).each(function() {
    $(this).find("Category").attr('name', 'ABC');
  });

  // For test only to see the change
  console.log((new XMLSerializer()).serializeToString($(xmlData)[0]));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;