簡體   English   中英

將字符串內容轉換為XMLStreamReader

[英]Convert the string content into an XMLStreamReader

您好我想知道我們如何轉換XML標簽形式的字符串內容,我需要將其轉換為XMLStreamReader

您可以使用XMLInputFactory.createXMLStreamReader ,傳入StringReader來包裝您的字符串。

String text = "<foo>This is some XML</foo>";
Reader reader = new StringReader(text);
XMLInputFactory factory = XMLInputFactory.newInstance(); // Or newFactory()
XMLStreamReader xmlReader = factory.createXMLStreamReader(reader);

我假設你想通過XMLStreamReaderString讀取XML內容。 你可以這樣做:

public XMLStreamReader readXMLFromString(final String xmlContent)
{
    final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    final StringReader reader = new StringReader(xmlContent);
    return inputFactory.createXMLStreamReader(reader);
}
//Intialize XMLInputFactory
XMLInputFactory factory = XMLInputFactory.newInstance();

//Reading from xml file and creating XMLStreamReader
XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream(
               file));
String currentElement = "";

//Reading all the data
while(reader.hasNext()) {
   int next = reader.next();
   if(next == XMLStreamReader.START_ELEMENT)
       currentElement = reader.getLocalName();
   //System.out.println(currentElement);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM