java - 使用属性作为标识符向 XML 添加行

标签 java android xml

我的 XML文件看起来像:

<?xml version="1.0" encoding="utf-8"?>
<Test1>
<task uuid="92F7F685-C370-4E55-9026-020E3CDCEDE0" status="1000">
    <task_status>200</task_status>    
</task>
<task uuid="92F7F685-C370-4E55-9026-020E3CDCEDE0" status="
    <task_status>200</task_status>
</task>
</Test1>

这个文件存放在私有(private)app目录下。我只想编辑此文件并将其存储在同一目录中的“较新”版本中。

我有这种方法来写入和读取 XML 文件:

private void writeToFile(String data, String fileName) {
    try {
        String UTF8 = "UTF-8";
        int BUFFER_SIZE = 8192;
        FileOutputStream fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream, UTF8), BUFFER_SIZE);
        bufferedWriter.write(data);
        bufferedWriter.close();
    } catch (IOException e) {
        Log.e("writeToFile: ", "Datei-Erstellung fehlgeschlagen: " + e.toString());
    }
}

//Datei lesen von Datei im privatem App-Verzeichnis
private String readFromFile(String fileName) {
    String ret = "";
    String UTF8 = "UTF-8";
    int BUFFER_SIZE = 8192;

    try {
        InputStream inputStream = openFileInput(fileName);

        if (inputStream != null) {
            BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(inputStream, UTF8), BUFFER_SIZE);
            String receiveString;
            StringBuilder stringBuilder = new StringBuilder();
            while ((receiveString = bufferedReader1.readLine()) != null) {
                stringBuilder.append(receiveString);
            }
            inputStream.close();
            ret = stringBuilder.toString();
        }
    } catch (FileNotFoundException e) {
        Log.e("readFromFile: ", "Datei nicht gefunden: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("readFromFile: ", "Kann Datei nicht lesen: " + e.toString());
        e.printStackTrace();
    }
    return ret;
}

如何添加新标签,如 <task_note> ?我想把它放在正确的任务中,所以我必须使用 uuid属性来标识我必须放置标签的位置。

XmlPullParser据我所知,这只是为了阅读,所以这没有帮助。

那么,我该怎么做呢?

编辑:

我得到这个错误:

  07-28 11:16:22.676  17703-17703/de.exampleapp W/System.err﹕ javax.xml.xpath.XPathExpressionException: java.net.MalformedURLException: Protocol not found: 000273E060E87000C0001323FA21427120150602153306.kx_task
07-28 11:16:22.676  17703-17703/de.exampleapp W/System.err﹕ at org.apache.xpath.jaxp.XPathImpl.evaluate(XPathImpl.java:481)
07-28 11:16:22.676  17703-17703/de.example.app W/System.err﹕ at de.example.app.TasksList.onActivityResult(TasksList.java:141)

我在这里得到这个:

InputSource inputSource = new InputSource(filename);

            String uuid = taskItems.get(position).get("uuid");
            XPath xPath = XPathFactory.newInstance().newXPath();
            try {
                Node taskNode = (Node) xPath.evaluate("//task[@uuid='" + uuid + "']", inputSource, XPathConstants.NODE);
                Document document = taskNode.getOwnerDocument();
                //Füge neue Zeile ein
                Node noteNode = document.createElement("task_note");
                noteNode.setTextContent(taskItems.get(position).get("task_note"));
                taskNode.appendChild(noteNode);
                //Speichere Datei
                Source input = new DOMSource(document);
                Result output = new StreamResult(new File(filename));
                TransformerFactory.newInstance().newTransformer().transform(input, output);
            } catch (XPathExpressionException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            }

        }

最佳答案

您可以使用 XPath ,以及 Android 中的其他 Java XML 标准库:

    // Read file
    InputSource inputStream = new InputSource(new FileInputStream(inputFileName));

    // Find the task node
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node taskNode = (Node)xpath.evaluate("//task[uuid='92F7F685-C370-4E55-9026-020E3CDCEDE0']", inputStream,
            XPathConstants.NODE);
    Document document = taskNode.getOwnerDocument();
    // Insert a new node
    Node noteNode = document.createElement("task_note");
    noteNode.setTextContent("this is a note");
    taskNode.appendChild(noteNode);

    // Save file
    Source input = new DOMSource(document);
    Result output = new StreamResult(new File(outputFileName));
    TransformerFactory.newInstance().newTransformer().transform(input, output);

关于java - 使用属性作为标识符向 XML 添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31653667/

相关文章:

java - 回收站 View : No adapter attached; skipping layout

android - 我可以在 genymotion 中添加任何 mi 设备虚拟设备吗

java - XMLEncryptionFactory 在哪里?

来自 xib 的 xml - 带键的字段名 nil

java - SWT 表在鼠标悬停时在 Windows 8 计算机中不显示工具提示

java - 如果没有单击按钮,则不会传递 EditText 数据

Java Fabric 8 - 使用 Fabric8 Java API 获取 Kubernetes 服务的 Pod 并启动服务

android - Android 媒体播放器上用于搜索栏的线程

android - 包括标签和数据绑定(bind)

java - JINI 还活跃吗?