簡體   English   中英

我如何在沒有XML的情況下解析XML文件 <?xml version=1.0> 對於Android

[英]How can I parse XML file without <?xml version=1.0> for android

使用SAX,DOM,XMLPull可以解析具有以下標頭的XML文件:

<JsonResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/System.Web.Mvc">
<ContentEncoding xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Text" i:nil="true"/>
<ContentType i:nil="true"/>
<Data xmlns:d2p1="http://schemas.datacontract.org/2004/07/ProximoColectivo.Entities" i:type="d2p1:FeatureCollection">

o應該始終以<?xml version = 1.0>開頭。

是的,您可以解析一個不以<?xml version = 1.0>開頭的xml文件。 例如

public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException {
    String str = "<abc/>";
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new ByteArrayInputStream(str.getBytes()));     
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
}

將工作。 但是您的String xml文件將無法工作。 為了使xml解析器正常工作,應該有一個根標簽,然后是其中的所有標簽。 所以

String str = "<abc/><pqr/>";

將無法工作,但

String str = "<abc><pqr/></abc>";

將工作。 作為解決方法,您可以做的是

Enumeration<InputStream> combinedStreams = Collections.enumeration(
    Arrays.asList(new InputStream[] {
        new ByteArrayInputStream("<abc>".getBytes()),
        yourXMLFileInputStreamStream,
        new ByteArrayInputStream("</abc>".getBytes()),
    }));

SequenceInputStream xmlStream = new SequenceInputStream(combinedStreams);
Document doc = dBuilder.parse(xmlStream);

暫無
暫無

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

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