简体   繁体   中英

Changing some Object field names during serialization

I am using javax.xml.bind.annotation.XmlRootElement annotated object to serialize it into XML string.

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

How to change some node name in the XML, so like I have "price" in the object, but "thePrice" in the XML document generated.

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

Use the name property of @XmlRootElement , @XmlElement and @XmlAttribute to define a different name in the XML document.

Example:

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

u cannot chage the name you can copy the atrybutes of element like if there is any like

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

you get those elements and place in another elemet that you will create and after that u delete the first one.

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

where parent is the parent node of price

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM