使用Java、JDom、XPath修改XML文件(命名空间)



我是XML解析领域的新手。我找到了读取带有"名称空间"的xml文件的解决方案,如下所示。我引用了这个stackoverflow链接Default XML命名空间、JDOM和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代码片段如下所示。

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();
      }
    }
}

这段代码运行良好,Reading元素"domainPseudomname"运行良好。

But I want to modify this element from 
 <DomainPseudonym>1331859289489</DomainPseudonym> to
 <DomainPseudonym>555555</DomainPseudonym>

我尝试使用函数xpath.setVariable("555555",doc)进行修改,但没有工作,也没有给出任何错误。最终结果是,它将相同的内容复制到新的xml文件"proofSpecOut.xml"中。

XPath不用于修改xml,只用于查找其中的一部分。XPath.setVariable()仅用于设置XPath表达式中的变量。您希望使用XPath.selectSingleNode()检索文档的某个元素,然后直接使用Element.setText()修改该元素。

最新更新