我正在使用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中的某些节点名称,就像我有"价格"在对象中,但是" thePrice"在生成的XML文档中。
答案 0 :(得分:1)
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");
答案 1 :(得分:1)
使用@XmlRootElement
,@XmlElement
和@XmlAttribute
的name属性在XML文档中定义其他名称。
示例:
public class MyClass {
@XmlElement(name="thePrice")
private double price;
}
答案 2 :(得分:1)
你不能乱用你可以复制元素的atrybutes的名字,如果有任何像
<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是价格的父节点