如何使用XMLBeam将元素插入现有文档?

时间:2019-10-27 18:30:19

标签: java xml

我需要使用 XMLBeam 将新元素插入到现有文档中。我可以从头开始创建文档,并可以阅读现有文档,但是在插入时遇到了麻烦。 如何插入示例XML中下面的注释所指示的新元素,例如ID为3?

说我有这个XML:

<p:PEOPLE xmlns:p="people-namespace">
    <p:PERSON id="1">
        <p:FIRST_NAME>John</p:FIRST_NAME>
        <p:LAST_NAME>Smith</p:LAST_NAME>
    </p:PERSON>
    <p:PERSON id="2">
        <p:FIRST_NAME>Sally</p:FIRST_NAME>
        <p:LAST_NAME>Green</p:LAST_NAME>
    </p:PERSON>
    <!-- How to add a new PERSON here with id = 3 ?? -->
</p:PEOPLE>

和这些投影界面:

interface PeopleData {

    @XBRead("/p:PEOPLE")
    List<Person> getAllPeople();

}


interface Person {

    @XBRead("@id")
    int getPersonId();

    @XBRead("p:FIRST_NAME")
    String getFirstName();

    @XBRead("p:LAST_NAME")
    String getLastName();
}

我正在按如下方式正常读取数据:

new XBProjector().io().file("some file name").read(PersonData.class);

我将Saxon用作XPath引擎,并在工厂配置中如下设置了名称空间上下文:

@Override
public XPath createXPath(Document... document) {
    XPathFactory factory = new XPathFactoryImpl();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new PeopleNamespaceContext());
    return xpath;
}

我尝试了几种不同的方法,但始终遇到此异常:

org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

1 个答案:

答案 0 :(得分:0)

您应该覆盖 DefaultXMLFactoriesConfig.getUserDefinedNamespaceMapping 方法

@Override
public Map<String, String> getUserDefinedNamespaceMapping() {
    return Collections.singletonMap("p", "people-namespace");
}

投影

interface PeopleData {

    @XBRead("/p:PEOPLE/p:PERSON")
    List<Person> getAllPeople();

    @XBWrite("/p:PEOPLE/p:PERSON[@id='{0}']")
    PeopleData setPerson(int id, @XBValue Person p);
}