我目前正在使用 EclipseLink MOXy 2.4.1 并尝试通过 XPaths 更新元素的值。使用的输入是:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<expenseReport>
<user>
<userName>Sanaulla</userName>
</user>
<items>
<item>
<itemName>Seagate External HDD</itemName>
<purchasedOn>August 24, 2010</purchasedOn>
<amount>6776.5</amount>
</item>
<item>
<itemName>External HDD</itemName>
<purchasedOn>August 24, 2010</purchasedOn>
<amount>677336.5</amount>
</item>
</items>
</expenseReport>
XSD 是
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="expenseReport" type="ExpenseT"/>
<xs:complexType name="ExpenseT">
<xs:sequence>
<xs:element name="user" type="UserT"/>
<xs:element name="items" type="ItemListT"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="UserT">
<xs:sequence>
<xs:element name="userName" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ItemListT">
<xs:sequence>
<xs:element name="item" type="ItemT" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ItemT">
<xs:sequence>
<xs:element name="itemName" type="xs:string"/>
<xs:element name="purchasedOn" type="xs:string"/>
<xs:element name="amount" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
我的Java代码是:
JAXBContext context = JAXBContext.newInstance("sample.jaxb.xsd");
JAXBElement<ExpenseT> element = (JAXBElement<ExpenseT>)unmarshaller.unmarshal(new File("resources/sample_before.xml"));
ExpenseT expenseReport = element.getValue();
context.setValueByXPath(expenseReport, "items/item[1]/amount/text()", null, "100.11");
/** Marshalling code **/
我使用 Moxy 的工具“jaxb-compiler.cmd”从 XSD 创建了我的 java 类。从上面的代码可以看出,我试图将第一项的数量设置为“100.11”。但它不设置值,也不抛出任何异常。我尝试使用这样的 XPath 设置上面的用户名
context.setValueByXPath(expenseReport, "user/userName/text()", null, "ABC");
而且,它确实正确设置/更新了值。您能否建议我如何使用谓词为复杂的 XPath 设置值?像这样的东西:
items/item[itemName='Seagate External HDD']/amount