2017-12-30 62 views
0

私のXML文書の構造は次のとおりです。特定の属性を持つ特定の要素でXML文書に書き込む方法は?

<?xml version="1.0" encoding="UTF-8"?> 
<PasswordVault> 
    <User id="1"> 
    <Log LOG="1"> 
     <AccountType>a</AccountType> 
     <Username>a</Username> 
     <Password>a</Password> 
     <E-mail>a</E-mail> 
    </Log> 
    <Log Log="2"> 
     <AccountType>b</AccountType> 
     <Username>b</Username> 
     <Password>b</Password> 
     <E-mail>b</E-mail> 
    </Log> 
    </User> 
    <User id="2"> 
    <Log LOG="2"> 
     <AccountType>a</AccountType> 
     <Username>a</Username> 
     <Password>a</Password> 
     <E-mail>a</E-mail> 
    </Log> 
    </User> 
</PasswordVault> 

私はそれに割り当てられた別の属性とその中の他の要素と別のログの要素を記述することが可能であることをJavaでコードを追加しようとしています。ただし、id = "2"の属性である正しいユーザー要素内になければなりません。 私はJDOMとSAXを使用していますが、これを行う方法を示すチュートリアルは見つからないようです。

public static void editXML(String inpName,String inpPassword,String inpEmail,String inpAccountType) { 
     try { 

      SAXBuilder builder = new SAXBuilder(); 
      File xmlFile = new File("FILE PATH"); 

      Document doc = (Document) builder.build(xmlFile); 
      Element rootNode = doc.getRootElement(); 

      // PROBLEM HERE - dont know how to find element by specific attribute 
      Element user = rootNode.getChild("User"); 



      // add new element 
      // hard coded just to test it 
      Element newLog = new Element("Log").setAttribute("Log","1"); 

      // new elements 
      Element accountType = new Element("AccountType").setText(inpAccountType); 
      newLog.addContent(accountType); 

      Element name = new Element("Username").setText(inpName); 
      newLog.addContent(name); 

      Element password = new Element("Password").setText(inpPassword); 
      newLog.addContent(password);     

      Element email = new Element("E-mail").setText(inpEmail); 
      newLog.addContent(email); 

      user.addContent(newLog); 

      XMLOutputter xmlOutput = new XMLOutputter(); 

      // display nice nice 
      xmlOutput.setFormat(Format.getPrettyFormat()); 
      xmlOutput.output(doc, new FileWriter("FILE PATH")); 

      // xmlOutput.output(doc, System.out); 

      System.out.println("File updated!"); 
      } catch (IOException io) { 
      io.printStackTrace(); 
      } catch (JDOMException e) { 
      e.printStackTrace(); 
      } 


} 

私は、XPathについて頭を持っていますが、私は非常に不慣れだと私は私の状況に関連する多くのオンラインを見つけることができませんでした。

答えて

1

id属性2を使用してUser要素を除外することができます。あなたはユーザー要素は、これが私の解決策で実施することができる方法を

Element user = null; 
if (userNode.isPresent()) { 
    user = userNode.get(); 
} else { 
    //handle failure 
} 

if (user != null) { 
    // create new elements and rest of the logic 
} 
+0

以下のように存在しているかどうかを確認する必要があります。その後

final Optional<Element> userNode = rootNode.getChildren("User").stream() .filter(user -> "2".equals(user.getAttributeValue("id"))).findFirst(); 

? – Harshmellow

+0

答えが –

+1

ありがとう、それが動作します:D – Harshmellow

関連する問題