这是我的代码;阅读结束如何在android源代码中编写本地xml文件中的写入和更新?

发布于 2025-01-08 07:21:09 字数 3003 浏览 0 评论 0原文

public class LocalXMLActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); // set the layout.. it refers main.xml
                                       // from the layout folder.
        InputStream is;
        DocumentBuilderFactory factory;
        DocumentBuilder builder;
        Document doc;
        NodeList allTitles = null;
        String dataAll;
        try {

            // Input Stream is used to read the bytes. getResources refers to
            // the android resources(res)folder and open RawResource to the raw
            // folder under res. (res/raw)
            is = this.getResources().openRawResource(R.raw.data);
            // Is to read the parser that prodcues from XML DOM.
            factory = DocumentBuilderFactory.newInstance();
            // Once an instance of this class is obtained, XML can be parsed
            // from a variety of input sources. These input sources are
            // InputStreams, Files, URLs, and SAX InputSources. There are many
            // sources to take data from internet.
            builder = factory.newDocumentBuilder();
            // the Document represents the entire HTML or XML document.
            // Conceptually, it is the root of the document tree, and provides
            // the primary access to the document's data.
            doc = builder.parse(is);
            // Retrieving the "company" node from xml
            allTitles = doc.getElementsByTagName("Company");

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        dataAll = "";
        for (int i = 0; i < allTitles.getLength(); i++) {
            dataAll += allTitles.item(i).getChildNodes().item(0).getNodeValue() + "\n";
        }

        TextView tv = (TextView)findViewById(R.id.myTextView); // finds the
                                                               // widget"myTextView"
                                                               // from main.xml
        tv.setText(dataAll); // setting the dataAll value to myTextView.
    }
}

xml文件:res/raw/data.xml

    <?xml version="1.0" ?>
<content>
    <item>
        <Company>Google</Company>
        <Feature>Search Engine / Mail / Social Media</Feature>
        <url>www.google.com</url>
    </item>
    <item>
        <Company>Yahoo</Company>
        <Feature>Search Engine / Mail</Feature>
        <url>www.yahoo.com</url>
    </item>
</content>

上面的代码只是读取代码,我有一个XML文件存储在我刚刚读取的res/raw/data.xml中,但是如何在本地xml文件中写入写入和更新内部读取源代码写入本地xml文件中写入和更新

public class LocalXMLActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); // set the layout.. it refers main.xml
                                       // from the layout folder.
        InputStream is;
        DocumentBuilderFactory factory;
        DocumentBuilder builder;
        Document doc;
        NodeList allTitles = null;
        String dataAll;
        try {

            // Input Stream is used to read the bytes. getResources refers to
            // the android resources(res)folder and open RawResource to the raw
            // folder under res. (res/raw)
            is = this.getResources().openRawResource(R.raw.data);
            // Is to read the parser that prodcues from XML DOM.
            factory = DocumentBuilderFactory.newInstance();
            // Once an instance of this class is obtained, XML can be parsed
            // from a variety of input sources. These input sources are
            // InputStreams, Files, URLs, and SAX InputSources. There are many
            // sources to take data from internet.
            builder = factory.newDocumentBuilder();
            // the Document represents the entire HTML or XML document.
            // Conceptually, it is the root of the document tree, and provides
            // the primary access to the document's data.
            doc = builder.parse(is);
            // Retrieving the "company" node from xml
            allTitles = doc.getElementsByTagName("Company");

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        dataAll = "";
        for (int i = 0; i < allTitles.getLength(); i++) {
            dataAll += allTitles.item(i).getChildNodes().item(0).getNodeValue() + "\n";
        }

        TextView tv = (TextView)findViewById(R.id.myTextView); // finds the
                                                               // widget"myTextView"
                                                               // from main.xml
        tv.setText(dataAll); // setting the dataAll value to myTextView.
    }
}

xml file:res/raw/data.xml

    <?xml version="1.0" ?>
<content>
    <item>
        <Company>Google</Company>
        <Feature>Search Engine / Mail / Social Media</Feature>
        <url>www.google.com</url>
    </item>
    <item>
        <Company>Yahoo</Company>
        <Feature>Search Engine / Mail</Feature>
        <url>www.yahoo.com</url>
    </item>
</content>

the above code is only reading code,I have an XML file stored in the res/raw/data.xml that I am just reading, but how to write writing and updating in local xml file with inside reading source code write to writing and updating in local xml file

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

向地狱狂奔 2025-01-15 07:21:09

您可以像这样在 SD 卡上创建一个新文件:

File Directory=  new File(Environment.getExternalStorageDirectory()
                        + File.separator + "working" +File.separator+"accounts");


File masterXMLfile = new File(Directory,"MasterCategories.xml");
                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                  //Get the DocumentBuilder
                  DocumentBuilder docBuilder = null;
                try {
                    docBuilder = factory.newDocumentBuilder();
                } catch (ParserConfigurationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  //Create blank DOM Document
                  Document doc = docBuilder.newDocument();


                  //create the root element
                  Element root = doc.createElement("Categories");
                  //all it to the xml tree
                  doc.appendChild(root);
                  for(int i =0; i < nodeArray.length;i++)
                  {
                      System.out.println("entered into if loop");
                      Element subroot = doc.createElement("Category");
                      root.appendChild(subroot);
                      Element nameNode = doc.createElement("Name");
                      nameNode.appendChild(doc.createTextNode(nodeArray[i]));
                      subroot.appendChild(nameNode);

                      Element thumbNailNode = doc.createElement("thumbnail");
                      thumbNailNode.appendChild(doc.createTextNode(nodeArray[i]+".jpg"));
                      subroot.appendChild(thumbNailNode);
                      Element descriptionNode = doc.createElement("description");
                      descriptionNode.appendChild(doc.createTextNode(nodeArray[i]+" data"));
                      subroot.appendChild(descriptionNode);
                  }
                  TransformerFactory transfactory = TransformerFactory.newInstance();
                    Transformer transformer= null;
                    try {
                        transformer = transfactory.newTransformer();
                    } catch (TransformerConfigurationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

                    // create string from xml tree
                    // StringWriter sw = new StringWriter();
                    // StreamResult result = new StreamResult(sw);
                    FileWriter categoriesFW = null;
                    try {
                        categoriesFW = new FileWriter(masterXMLfile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    StreamResult result = new StreamResult(categoriesFW);
                    DOMSource source = new DOMSource(doc);
                    try {
                        transformer.transform(source, result);
                    } catch (TransformerException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                if(!masterXMLfile.exists())
                {
                    try {
                        masterXMLfile.createNewFile();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

You can create a new file on SD card like this:

File Directory=  new File(Environment.getExternalStorageDirectory()
                        + File.separator + "working" +File.separator+"accounts");


File masterXMLfile = new File(Directory,"MasterCategories.xml");
                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                  //Get the DocumentBuilder
                  DocumentBuilder docBuilder = null;
                try {
                    docBuilder = factory.newDocumentBuilder();
                } catch (ParserConfigurationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  //Create blank DOM Document
                  Document doc = docBuilder.newDocument();


                  //create the root element
                  Element root = doc.createElement("Categories");
                  //all it to the xml tree
                  doc.appendChild(root);
                  for(int i =0; i < nodeArray.length;i++)
                  {
                      System.out.println("entered into if loop");
                      Element subroot = doc.createElement("Category");
                      root.appendChild(subroot);
                      Element nameNode = doc.createElement("Name");
                      nameNode.appendChild(doc.createTextNode(nodeArray[i]));
                      subroot.appendChild(nameNode);

                      Element thumbNailNode = doc.createElement("thumbnail");
                      thumbNailNode.appendChild(doc.createTextNode(nodeArray[i]+".jpg"));
                      subroot.appendChild(thumbNailNode);
                      Element descriptionNode = doc.createElement("description");
                      descriptionNode.appendChild(doc.createTextNode(nodeArray[i]+" data"));
                      subroot.appendChild(descriptionNode);
                  }
                  TransformerFactory transfactory = TransformerFactory.newInstance();
                    Transformer transformer= null;
                    try {
                        transformer = transfactory.newTransformer();
                    } catch (TransformerConfigurationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

                    // create string from xml tree
                    // StringWriter sw = new StringWriter();
                    // StreamResult result = new StreamResult(sw);
                    FileWriter categoriesFW = null;
                    try {
                        categoriesFW = new FileWriter(masterXMLfile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    StreamResult result = new StreamResult(categoriesFW);
                    DOMSource source = new DOMSource(doc);
                    try {
                        transformer.transform(source, result);
                    } catch (TransformerException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                if(!masterXMLfile.exists())
                {
                    try {
                        masterXMLfile.createNewFile();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
莫相离 2025-01-15 07:21:09

好吧,老实说,这写得非常混乱,但这是我的想法:

FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/path/file.xml");
fos.write(byte_array_from_input);
fos.close();

这会将文件写入您的 sdcard 到 /path/file.xml。您放入一个字节数组,对于小文件,您可以一次性执行此操作;如果您有大量数据,则可以在循环中执行此操作。

Well, honestly that is very confusingly written, but here is my thoughts:

FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/path/file.xml");
fos.write(byte_array_from_input);
fos.close();

That will write a file to your sdcard to /path/file.xml. You put in a byte array which you can either do in one go for small files, or in a loop if you have a large set of data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文