3

我有一个 XML(实际上是 a 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();
    }
}
4

2 回答 2

2

XmlPullParser 不能修改值。您需要同时解析和写入。同时使用 DomDocument 或基于流的读取器和写入器。

DomDocument 最适合您。

于 2016-03-03T11:35:37.637 回答
1

这是所需的解决方案。我是用 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>
于 2016-03-04T10:20:04.083 回答