更新\修改Android中的XML文件

Kha*_*Tam 3 java xml android xml-parsing

我想知道如何实时更新XML文件.我有这个文件例如:

<?xml version="1.0" encoding="UTF-8"?>
    <Cars>
        <car make="Toyota" model="95" hp="78" price="120"/>
        <car make="kia" model="03" hp="80" price="300"/>
    </Cars>
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能像这样更新价格值?:

<?xml version="1.0" encoding="UTF-8"?>
    <Cars>
        <car make="Toyota" model="95" hp="78" price="50"/>
        <car make="kia" model="03" hp="80" price="100"/>
    </Cars>
Run Code Online (Sandbox Code Playgroud)

我搜索过网络,但我找到的只是如何解析,以及如何编写整个文件XmlSerializer,但不是如何修改.我也用Java 发现了这个,但是我没能在Android上实现它,因为我对android-xml世界很新.

Kha*_*Tam 8

在漫长的一天搜索和尝试后,我可以使用Java的DOM达到目标.要修改XML文件,首先要实例化这些文件以处理XML:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(context.openFileInput("MyFileName.xml")); // In My Case it's in the internal Storage
Run Code Online (Sandbox Code Playgroud)

然后通过以下方式NodeList为所有"汽车"元素制作:

NodeList nodeslist = doc.getElementsByTagName("car");
Run Code Online (Sandbox Code Playgroud)

或者通过更换汽车的所有元素String"*".

现在它可以很好地搜索每个节点属性,直到它精确到"price"KIA 的值为例:

for(int i = 0 ; i < nodeslist.getLength() ; i ++){
            Node node = nodeslist.item(i);
            NamedNodeMap att = node.getAttributes();
            int h = 0;
            boolean isKIA= false;
            while( h < att.getLength()) {
                Node car= att.item(h);
                if(car.getNodeValue().equals("kia"))
                   isKIA= true;      
                if(h == 3 && setSpeed)   // When h=3 because the price is the third attribute
                   playerName.setNodeValue("100");   
                 h += 1;  // To get The Next Attribute.
           }
}
Run Code Online (Sandbox Code Playgroud)

确定最后,使用以下方法将新文件保存在同一位置Transformer:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource dSource = new DOMSource(doc);
StreamResult result = new StreamResult(context.openFileOutput("MyFileName.xml", Context.MODE_PRIVATE));  // To save it in the Internal Storage
transformer.transform(dSource, result);
Run Code Online (Sandbox Code Playgroud)

而已 :) .我希望这会有所帮助.