[英]Append node to an existing xml-Java
我已經看到了針對vb和c#的相同問題,但是我需要一個Java最佳解決方案來將節點附加到xml。 請問xpath有幫助嗎? 我有
<A>
<B>
<c>1<c/>
<d>2<d/>
<e>3<e/>
</B>
<B>
<c>1<c/>
<d>2<d/>
<e>3<e/>
</B>
</A>
需要追加另一個
<B>
<c>11<c/>
<d>21<d/>
<e>31<e/>
</B>
XPath將幫助您查找節點,但不會真正附加它們。 我不認為你在這里發現它特別有用。
您使用的是哪種XML API? 如果它是W3C DOM(urgh)那么你會做類似的事情:
Element newB = document.createElement("B");
Element newC = document.createElement("c");
newC.setTextContent("11");
Element newD = document.createElement("d");
newD.setTextContent("21");
Element newE = document.createElement("e");
newE.setTextContent("31");
newB.appendChild(newC);
newB.appendChild(newD);
newB.appendChild(newE);
document.getDocumentElement().appendChild(newB);
最直接的方法是使用Sax或Dom將所有文件解析為數據結構,例如A類,其中包含一個B類,在您的情況下具有C,D,E類成員。
並將數據結構輸出回XML。
您可能希望使用vtd-xml的XMLModier以一種很酷的方式執行它,即直接附加字節內容...您只需要調用XMLModier的insertAfterElement()...下面是代碼示例的鏈接: 用Java增量修改XML :
import com.ximpleware.*;
import java.io.*;
public class ModifyXML {
public static void main(String[] s) throws Exception{
VTDGen vg = new VTDGen(); // Instantiate VTDGen
XMLModifier xm = new XMLModifier(); //Instantiate XMLModifier
if (vg.parseFile("old.xml",false)){
VTDNav vn = vg.getNav();
xm.bind(vn);
// first update the value of attr
int i = vn.getAttrVal("attr");
if (i!=-1){
xm.updateToken(i,"value");
}
// navigate to <a>
if (vn.toElement(VTDNav.FC,"a")) {
// update the text content of <a>
i=vn.getText();
if (i!=-1){
xm.updateToken(i," new content ");
}
// insert an element before <a> (which is the cursor element)
xm.insertBeforeElement("<b/>\n\t");
// insert an element after <a> (which is the cursor element)
xm.insertAfterElement("\n\t<c/>");
}
xm.output(new FileOutputStream("new.xml"));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.