如何在Java中更改DOM节点?

时间:2011-11-26 16:30:19

标签: java android xml-parsing

我编辑了EditText节点的text属性,现在我想把它提交给DOM,我不知道怎么做。这就是我到目前为止所做的:

InputStream fXmlFile = resources.openRawResource(R.raw.pages);

            //Reads xml file and gets the node types and attributes
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("*");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);   
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    if(eElement.getNodeName().compareTo("EditText")==0)
                    {
                        String resName = eElement.getAttribute(ANDROID_ID);
                        resName = resName.replace("@+id/", "");
                        System.out.println(eElement.getNodeName()+" " + eElement.getAttribute(ANDROID_ID));
                        int resID = resources.getIdentifier(resName, "id", "mfc.generalgui2");
                        //get value from edittext field
                        String value = ((EditText) findViewById(resID)).getText().toString();
                        //set text attribute to value
                        eElement.setAttribute("android:text", value);
                    }
                }
            }
        } 
        catch (Exception e) {
            System.out.println("Catch");
            e.printStackTrace();
        }   

将DOM转换为字符串代码:

TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");


            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            String xmlString = sw.toString();
            System.out.println(xmlString);

1 个答案:

答案 0 :(得分:0)

我忘记了文档的链接。但是如果我没记错的话,你就无法对资源进行更改 - 就像你使用的代码R.raw.pages一样。

要将DOM树保存到文件,可以使用以下代码:

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import java.io.File;
import java.io.FileOutputStream;

...

//your document
Document doc = dBuilder.parse(fXmlFile);

OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);

FileOutputStream fos = new FileOutputStream(new File("your-file"));
try {
  XMLSerializer serializer = new XMLSerializer(fos, format);
  serializer.serialize(doc);
} finally {
  fos.close();
}

我正在使用Apache XML。