![](/img/trans.png)
[英]How to make the Java to call a String from a XML file(In Android Studio)
[英]How to make XML document from string in java or Android?
我正在嘗試從 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");
}
這段代碼工作得很好。 但現在我有一個這樣的字符串:
String xmlRecords = "<data><terminal_id>1000099999</terminal_id><merchant_id>10004444</merchant_id><merchant_info>Mc Donald's - Abdoun</merchant_info></data>";
我想從此xmlRecords
變量創建一個.xml
文件。 我該怎么做呢?
您可以將 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)));
您可以保留問題中提到的文件寫入部分,只需將Document
實例的創建替換為上述代碼即可。
如果您使用的是XmlPullParser
,這是另一種解決方案:
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader("<your><xml><string>Hello</string></xml></your>"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.