Prostitutor
Prostitutor

Reputation: 383

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.

Upvotes: 1

Views: 1805

Answers (3)

Mihai Ilie
Mihai Ilie

Reputation: 38

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

Upvotes: 1

wero
wero

Reputation: 32980

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

Upvotes: 2

Mihai Ilie
Mihai Ilie

Reputation: 38

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

Upvotes: 1

Related Questions