序列化期间更改某些对象字段名称
问题描述:
我正在使用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改变一些节点的名字,所以像我有生成的XML文档中的目标“价格”,而是“thePrice”。
答
使用的@XmlRootElement
,@XmlElement
和@XmlAttribute
name属性的XML文档中定义不同的名称。
例子:
public class MyClass {
@XmlElement(name="thePrice")
private double price;
}
答
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");
+0
的父节点? – wero
答
你无法恰克的名字,你可以复制元素的atrybutes一样,如果有任何类似
<price id="12" style="color:blue"> 12.16$</price>
你在另一个elemet这些元素和地方,你会创建之后,你删除第一个。
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);
}
其中父母是如何改变这个节点名称价格
对我来说只适用于二传手。 – Prostitutor