简体   繁体   English

在序列化期间更改一些对象字段名称

[英]Changing some Object field names during serialization

I am using javax.xml.bind.annotation.XmlRootElement annotated object to serialize it into XML string. 我正在使用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();

How to change some node name in the XML, so like I have "price" in the object, but "thePrice" in the XML document generated. 如何更改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");

Use the name property of @XmlRootElement , @XmlElement and @XmlAttribute to define a different name in the XML document. 使用的名称属性@XmlRootElement@XmlElement@XmlAttribute的XML文档中定义不同的名称。

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 其中parent是价格的父节点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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