【问题标题】:Update\Modify an XML file in Android在 Android 中更新\修改 XML 文件
【发布时间】:2016-03-19 21:58:07
【问题描述】:

我想知道如何实时更新 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>

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

<?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>

我在网上搜索过,但我发现的只是如何解析,以及如何使用XmlSerializer 编写整个文件,而不是如何修改。我还在 Java 中找到了this,但我未能在 Android 上实现它,因为我对 android-xml 世界很陌生。

【问题讨论】:

  • 遗憾的是没有简单 方法来更新xml 文件。必须将 xml 分解为节点,这变得非常令人麻木。您提供的链接是一个很好的起点,但请提供您的一些代码,以便我们帮助您完善它。
  • @GregoryNikitas 谢谢你的评论,不幸的是我所有的尝试都以失败告终,所以我现在没有用于编写 xml 的代码,并且为了解析我正在使用 XmlPullParser 作为官方的 android 开发方式,并且没关系。

标签: java android xml xml-parsing


【解决方案1】:

经过漫长的一天搜索和尝试,我已经使用 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

然后为所有“汽车”元素创建一个NodeList

NodeList nodeslist = doc.getElementsByTagName("car");

或所有元素,将汽车String 替换为"*"

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

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.
           }
}

OK 最后,使用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);

就是这样:)。我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 2011-01-08
    • 2015-10-19
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多