如何在具有特定属性的特定元素上写入XML文档?

时间:2017-12-30 15:47:12

标签: java 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中添加能够编写另一个Log元素的代码,该代码具有分配给它的另一个属性以及其中的其他元素。但是它必须位于正确的User元素内,该元素是id =&#34; 2&#34;的属性。 我一直在使用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 个答案:

答案 0 :(得分:1)

您可以使用以下代码过滤掉User元素id属性。

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

之后,您需要检查用户元素是否存在,如下所示

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

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