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

标签 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 =“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 有了解,但我很陌生,而且我在网上找不到太多与我的情况相关的信息。

最佳答案

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

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
}

关于java - 如何在具有特定属性的特定元素处写入 XML 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48035406/

相关文章:

java - 文件选取器无法筛选和选取 intent.setType ("application/excel")

java - 使用外部文件打包 Eclipse 程序

xml - XSLT - 重命名节点并删除空格等等

sql-server - 在 SQL Server 2005 中查询 XML 列

javascript - 使用 Javascript 和 HTML 读取和处理 XML

java - 作业参数正在被缓存

java - Android stub 问题

Java - 在声明行中对静态数组进行排序(而不是在静态构造函数中)

c++ - 将 C++ 转换为 Objective C

java - 如何将字符串(XML)转换为 SOAP 消息