繁体   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