Remove XML attribute using JDOM API?

自古美人都是妖i 提交于 2019-12-25 00:40:19

问题


I have a JDOM element like the following

Example:XML(JDOM Element)

<Details>
<Uniqueno>11111</Uniqueno>
<ROWSET name="Persons">
<ROW num="1">
<Name>60821894</Name>
<Age>938338789</Age>
</ROW>
<ROW num="2">
<Name>60821894</Name>
<Age>938338789</Age>
</ROW>
</ROWSET>
</Details>

I want to convert like:

<Details>
<Uniqueno>11111</Uniqueno>

<ROW num="1">
<Name>60821894</Name>
<Age>938338789</Age>
</ROW>
<ROW num="2">
<Name>60821894</Name>
<Age>938338789</Age>
</ROW>

</Details>

note:ROWSET element is removed

I want to remove the element using JDOM API?


回答1:


What have you already tried ?

  1. Find the Details tag (which is the document root)
  2. Find the ROWSET tag
  3. for each ROW tag in ROWSET call the detach() method on the node and append() this detached node to the Details tag.
  4. Delete the ROWSET tag.

With some sample code:

// 1
Element details = doc.getRootElement();
// 2
Element rowset = details.getChild("ROWSET");
// 3
for (Element row: rowset.getChildren()) {
    Element r = row.detach();
    details.appendChild(r);
}
// 4
details.removeChild(rowset);

Not tested, for more info check the JDOM API.




回答2:


If you are using JDOM 2.0.x you can do something like:

for (Element rowset : details.getChildren("ROWSET")) {
    rowset.detach();
    for (Content c : rowset.getContent()) {
         details.addContent(c.detach());
    }
}

If you are using JDOM 1.x you can do something similar, but with more casts....



来源:https://stackoverflow.com/questions/10514756/remove-xml-attribute-using-jdom-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!