使用XmlPullParser修改xml属性值

时间:2016-02-26 12:16:56

标签: android xmlpullparser android-xmlpullparser

我有一个XML(实际上是String),我想查找包含属性widthheight的所有标记,并修改它们的值。

XML示例:

<div>
<div class="separator" style="clear: both; text-align: center;">
    <a href="http://1.bp.blogspot.com/-b5iKjQ5ivZQ/VOoBX9NinU3232I/AAAAAAAADZU332/zq3apERWFms/s800/IMG_3426.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;">
        <img border="0" height="426" src="http://1.bp.blogspot.com/-b5iKjQ5ivZQ/VOoBX9NinUI/AAAAAAAADZU/zq32323apERWFms/s800/IMG_3426.JPG" width="640" />
    </a>
</div>
<div class="separator" style="clear: both; text-align: center;">
    <iframe allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/sI9Qf7UmXl0" width="420"></iframe>
</div>

在上面的示例中,我想修改:

  • 426和640值
  • 560和315值

我能够使用XmlPullParser识别一些值:下面的代码标识426和640值,但不是560和315。 另外我不知道如何用XML修改它们:

public void parse(String inputString) throws XmlPullParserException, IOException {
    XmlPullParser parser = Xml.newPullParser();
    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
    parser.setInput(new StringReader(inputString));
    parser.nextTag();
    readXml(parser);
}

private void readXml(XmlPullParser parser) throws XmlPullParserException, IOException {
    int eventType = parser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        switch (eventType) {
            case XmlPullParser.START_TAG:
                break;

            case XmlPullParser.END_TAG:
                String h = parser.getAttributeValue(null, "height");
                String w = parser.getAttributeValue(null, "width");
                if (!TextUtils.isEmpty(h) && !TextUtils.isEmpty(w)) {
                    // TODO: need to change here h and w values in XML
                }
                break;
        }
        eventType = parser.next();
    }
}

2 个答案:

答案 0 :(得分:2)

XmlPullParser无法修改值。你需要解析并同时写。同时使用DomDocument或基于流的读者和作者。

DomDocument最适合你。

答案 1 :(得分:0)

这是必需的解决方案。我在JAVA中写过这个,但你可以在android中使用它进行微小的更改。既然你没有写出你想对文件做出什么改变,我假设乘以2,但你也可以改变它:

private static Document doc = null;
public static void main(String[] args) {
    try {   
        String s = "<File>\n" +
                "<div class=\"separator\" style=\"clear: both; text-align: center;\">\n" +
                "    <a href=\"http://1.bp.blogspot.com/-b5iKjQ5ivZQ/VOoBX9NinU3232I/AAAAAAAADZU332/zq3apERWFms/s800/IMG_3426.JPG\" imageanchor=\"1\" style=\"margin-left: 1em; margin-right: 1em;\">\n" +
                "        <img border=\"0\" height=\"426\" src=\"http://1.bp.blogspot.com/-b5iKjQ5ivZQ/VOoBX9NinUI/AAAAAAAADZU/zq32323apERWFms/s800/IMG_3426.JPG\" width=\"640\" />\n" +
                "    </a>\n" +
                "</div>\n" +
                "<div class=\"separator\" style=\"clear: both; text-align: center;\">\n" +
                "    <iframe allowfullscreen=\"\" frameborder=\"0\" height=\"315\" src=\"https://www.youtube.com/embed/sI9Qf7UmXl0\" width=\"420\"></iframe>\n" +
                "</div>\n" +
                "</File>";
         InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
         DocumentBuilderFactory dbFactory 
            = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

         doc = dBuilder.parse(stream);
         doc.getDocumentElement().normalize();

         Element root = doc.getDocumentElement();

         //First, browse the children and modify the required attributes
         browseChildNodesAndModifyValue(root);

         //Now, write to a file, or do something with it
         writeDomToFile();

      } catch (Exception e) {
         e.printStackTrace();
      }


}

private static void browseChildNodesAndModifyValue(Node parent){
    NodeList nodeList = parent.getChildNodes();

    if(nodeList.getLength() > 0){
        for(int temp = 0; temp< nodeList.getLength(); temp++){
            Node node = nodeList.item(temp);
            browseChildNodesAndModifyValue(node);
        }
    }else{
        NamedNodeMap nodeMap = parent.getAttributes();

        if(nodeMap == null) return;

        for(int temp2=0; temp2< nodeMap.getLength(); temp2++){
            Node n = nodeMap.item(temp2);
            String attributeName = n.getNodeName();

            if(attributeName.equals("height")){
                int height = Integer.parseInt(n.getNodeValue());
                System.out.println("Height = "+height);

                //Modify the height here. e.g. I will multiply by 2
                n.setNodeValue(String.valueOf(height*2));
            }else if(attributeName.equals("width")){
                int width = Integer.parseInt(n.getNodeValue());
                System.out.println("width = "+width);

                //Modify the width here. e.g. I will multiply by 2
                n.setNodeValue(String.valueOf(width*2));
            }

        }
    }
}

private static void writeDomToFile() throws TransformerException{
    TransformerFactory transformerfactory=
            TransformerFactory.newInstance();
    Transformer transformer=
            transformerfactory.newTransformer();

    DOMSource source=new DOMSource(doc);

    StreamResult result=new StreamResult(new File("C:\\abc.xml"));

    /*
     * For Android, you can use this :

        FileOutputStream _stream=getApplicationContext().openFileOutput("NewDom.xml", getApplicationContext().MODE_WORLD_WRITEABLE);
        StreamResult result=new StreamResult(_stream);

     */

    transformer.transform(source, result);
}

我收到的输出文件是:

<File>
<div class="separator" style="clear: both; text-align: center;">
    <a href="http://1.bp.blogspot.com/-b5iKjQ5ivZQ/VOoBX9NinU3232I/AAAAAAAADZU332/zq3apERWFms/s800/IMG_3426.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;">
        <img border="0" height="852" src="http://1.bp.blogspot.com/-b5iKjQ5ivZQ/VOoBX9NinUI/AAAAAAAADZU/zq32323apERWFms/s800/IMG_3426.JPG" width="1280"/>
    </a>
</div>
<div class="separator" style="clear: both; text-align: center;">
    <iframe allowfullscreen="" frameborder="0" height="630" src="https://www.youtube.com/embed/sI9Qf7UmXl0" width="840"/>
</div>
</File>