【发布时间】:2012-04-02 11:47:33
【问题描述】:
我是 XML 解析领域的新手。我找到了使用“命名空间”读取 xml 文件的解决方案,如下所示。我参考了这个 stackoverflow 链接Default XML namespace, JDOM, and XPath 并阅读了 Element 的作品。但我无法修改元素。这是我的问题陈述。
我的 xml 文件如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<ProofSpecification xmlns="http://www.zurich.ibm.com/security/idemix"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.zurich.ibm.com/security/idemix ProofSpecification.xsd">
<Declaration>
<AttributeId name="id1" proofMode="unrevealed" type="string" />
<AttributeId name="id2" proofMode="unrevealed" type="string" />
</Declaration>
<Specification>
<Credentials>
<Credential issuerPublicKey="file:/Users/ipk.xml"
credStruct="file:/Users/CredStruct_ResUAC.xml" name="SpecResUAC">
<Attribute name="FirstName">id1</Attribute>
<Attribute name="LastName">id2</Attribute>
</Credential>
</Credentials>
<Pseudonyms>
<Pseudonym name="pseudonym"></Pseudonym>
<DomainPseudonym>1331859289489</DomainPseudonym>
</Pseudonyms>
<Messages />
</Specification>
</ProofSpecification>
而我的 java 代码 sn-p 看起来像这样。
public class ModifyXMLFileJDom {
public static void main(String[] args) throws JDOMException, IOException {
try {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("/blabla/ProofSpecResUAC_old.xml");
Document doc = (Document) builder.build(xmlFile);
XPath xpath = XPath.newInstance("x:ProofSpecification/x:Specification/x:Pseudonyms/x:DomainPseudonym");
xpath.addNamespace("x", doc.getRootElement().getNamespaceURI());
System.out.println("domainPseudonym: "+xpath.valueOf(doc));
xpath.setVariable("555555", doc);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("/blabla/proofSpecOut.xml"));
System.out.println("File updated!");
} catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
}
}
这段代码工作正常,阅读元素“domainPseudonym”工作正常。
But I want to modify this element from
<DomainPseudonym>1331859289489</DomainPseudonym> to
<DomainPseudonym>555555</DomainPseudonym>
我尝试使用函数 xpath.setVariable("555555", doc) 进行修改,但没有工作并且没有给出任何错误。最终结果是将相同的内容复制到新的 xml 文件“proofSpecOut.xml”中。
【问题讨论】:
标签: java xpath xml-parsing jdom