2012-03-16 11 views
0

私はXML解析の世界で初心者です。私は以下のように 'namespace'を持つxmlファイルを読むためのソリューションを見つけました。私はこのstackoverflowのリンクDefault XML namespace, JDOM, and XPathとElementの読書を参照しています。しかし、私は要素を変更することができません。ここに私の問題のステートメントがあります。Java、JDom、XPathを使用したXMLファイル(名前空間)の変更

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

このコードはうまく機能し、 "DomainPseudonym"の読み込み機能が動作します。

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

私は機能xpath.setVariable(「555555」、DOC)を使用して変更しようとしましたが、エラーを配って作業していないではありません。最終的には、同じ内容を新しいxmlファイル "proofSpecOut.xml"にコピーします。

答えて

2

XPathはxmlを変更するためには使用されませんが、その部分を見つけるためにのみ使用されます。 XPath.setVariable()は、xpath式で変数を設定するためのものです。 XPath.selectSingleNode()を使用してドキュメントの要素の1つを取得し、次にElement.setText()を使用してその要素を直接変更したいとします。

+0

ありがとうございました。出来た!私はこれを苦労して、さまざまなパーサーや他の例を試してみました。 :D – iankits

関連する問題