2016-03-15 81 views
0

我正在使用javax.xml.bind.annotation.XmlRootElement帶註釋的對象將其序列化爲XML字符串。序列化期間更改某些對象字段名稱

 JAXBContext jc = JAXBContext.newInstance(obj.getClass()); 
     // Marshal the object to a StringWriter 
     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); 
     marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.com/schema.xsd"); 
     StringWriter stringWriter = new StringWriter(); 
     marshaller.marshal(obj, stringWriter); 
     result = stringWriter.toString(); 

如何在XML改變一些節點的名字,所以像我有生成的XML文檔中的目標「價格」,而是「thePrice」。

回答

1

使用的@XmlRootElement@XmlElement@XmlAttribute name屬性的XML文檔中定義不同的名稱。

例子:

public class MyClass { 
    @XmlElement(name="thePrice") 
    private double price; 
} 
+0

對我來說只適用於二傳手。 – Prostitutor

1
try { 
    String filepath = "c:\\file.xml"; 
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 
    Document doc = docBuilder.parse(filepath); 

    // Get the root element 
    Node company = doc.getFirstChild(); 


    // getElementsByTagName() to get it directly. 

    // Get the staff element by tag name directly 
    Node price = doc.getElementsByTagName("price").item(0); 

    // update price attribute 
    NamedNodeMap attr = price.getAttributes(); 
    Node nodeAttr = attr.getNamedItem("id"); 
    nodeAttr.setTextContent("some other price"); 
+0

的父節點? – wero

1

你無法恰克的名字,你可以複製元素的atrybutes一樣,如果有任何類似

<price id="12" style="color:blue"> 12.16$</price> 

你在另一個elemet這些元素和地方,你會創建之後,你刪除第一個。

contentFromPrice = price.getTextContent(); 

    Element price2 = doc.createElement("price2"); 
    age.appendChild(doc.createTextNode("contentFromPrice")); 
    parent.appendChild(price2); 

     //remove first price 
     if ("price".equals(price.getNodeName())) { 
     parent.removeChild(price); 
     } 

其中父母是如何改變這個節點名稱價格