簡體   English   中英

在序列化期間更改一些對象字段名稱

[英]Changing some Object field names during serialization

我正在使用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中的某些節點名稱,就像我在對象中具有“ price”,而在XML文檔中生成“ thePrice”一樣。

   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");

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

例:

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

您無法更改名稱,您可以復制元素的屬性,例如是否存在類似

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

您將獲得這些元素,並將其放置在將要創建的另一個要素中,然后刪除第一個要素。

  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);
       }

其中parent是價格的父節點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM