如何从java或Android中的字符串生成XML文档?

Sit*_*ten 4 java xml android file

我试图从Java创建一个动态生成的XML文件.这是我尝试使用的代码:

try{
            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

            System.out.println("how many elements: ");
            String str = bf.readLine();
            int no = Integer.parseInt(str);

            System.out.println("enetr root: ");
            String root = bf.readLine();

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document d1 = db.newDocument();
            Element e1 = d1.createElement(root);
            d1.appendChild(e1);

            for (int i = 0; i < no; i++) {
                System.out.println("enter element: ");
                String element = bf.readLine();

                System.out.println("enter data: ");
                String data = bf.readLine();
                Element em = d1.createElement(element);
                em.appendChild(d1.createTextNode(data));

                e1.appendChild(em);
            }
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(d1);

            File file = new File("src\\xml\\copy.xml");
            System.out.println(file);

            if(!file.exists()){
                file.createNewFile();
            }
            OutputStream outputStream = new FileOutputStream(file);
            StreamResult result = new StreamResult(outputStream);
            transformer.transform(source, result);
            outputStream.close();

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            System.out.println("file not created");
        }
Run Code Online (Sandbox Code Playgroud)

这段代码效果很好.但是现在我有一个字符串:

String xmlRecords = "<data><terminal_id>1000099999</terminal_id><merchant_id>10004444</merchant_id><merchant_info>Mc Donald's - Abdoun</merchant_info></data>";
Run Code Online (Sandbox Code Playgroud)

我想.xml从这个xmlRecords变量创建一个文件.我该怎么做呢?

wja*_*ans 15

您可以将XML字符串解析为Document:

String xmlRecords = "<data><terminal_id>1000099999</terminal_id><merchant_id>10004444</merchant_id><merchant_info>Mc Donald's - Abdoun</merchant_info></data>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document d1 = builder.parse(new InputSource(new StringReader(xmlRecords)));
Run Code Online (Sandbox Code Playgroud)

您可以保留问题中提到的文件编写部分,只需Document用上面的代码替换实例的创建.


ple*_*ock 5

如果您使用以下是另一种解决方案XmlPullParser:

XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader("<your><xml><string>Hello</string></xml></your>"));
Run Code Online (Sandbox Code Playgroud)