JAXB是否支持在不进行编组/解组的情况下修改现有XML文档?

时间:2011-05-19 13:38:43

标签: java xml jaxb

我想在文档中保留注释,排序等,并使用Java界面就地编辑文档。

JAXB会这样做吗?

其他工具如XMLBeans会这样做吗?

1 个答案:

答案 0 :(得分:7)

您可以将JAXB Binder用于此用例:

<强> input.xml中

<?xml version="1.0" encoding="UTF-8"?>
<customer>
    <UNMAPPED_ELEMENT_1/>
    <name>Jane Doe</name>
    <!-- COMMENT #1 -->
    <address>
        <UNMAPPED_ELEMENT_2/>
        <street>1 A Street</street>
        <!-- COMMENT #2 -->
        <UNMAPPED_ELEMENT_3/>
        <city>Any Town</city>
    </address>
    <!-- COMMENT #3 -->
    <UNMAPPED_ELEMENT_4/>
    <phone-number type="home">555-HOME</phone-number>
    <!-- COMMENT #4 -->
    <phone-number type="cell">555-CELL</phone-number>
    <UNMAPPED_ELEMENT_5/>
    <!-- COMMENT #5 -->
</customer>

<强>演示

import java.io.File;
import javax.xml.bind.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

public class BinderDemo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File xml = new File("input.xml");
        Document document = db.parse(xml);

        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        Binder<Node> binder = jc.createBinder();
        Customer customer = (Customer) binder.unmarshal(document);
        customer.getAddress().setStreet("2 NEW STREET");
        PhoneNumber workPhone = new PhoneNumber();
        workPhone.setType("work");
        workPhone.setValue("555-WORK");
        customer.getPhoneNumbers().add(workPhone);
        binder.updateXML(customer);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(document), new StreamResult(System.out));
    }     
}

<强>输出

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<customer>
    <UNMAPPED_ELEMENT_1/>
    <name>Jane Doe</name>
    <!-- COMMENT #1 -->
    <address>
        <UNMAPPED_ELEMENT_2/>
        <street>2 NEW STREET</street>
        <!-- COMMENT #2 -->
        <UNMAPPED_ELEMENT_3/>
        <city>Any Town</city>
    </address>
    <!-- COMMENT #3 -->
    <UNMAPPED_ELEMENT_4/>
    <phone-number type="home">555-HOME</phone-number>
    <!-- COMMENT #4 -->
    <phone-number type="cell">555-CELL</phone-number>
    <phone-number type="work">555-WORK</phone-number>
    <UNMAPPED_ELEMENT_5/>
    <!-- COMMENT #5 -->
</customer>

了解更多信息