简体   繁体   中英

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

It is possible with SAX, DOM, XMLPull parse a XML file with the following header:

<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 should always start with <?xml version = 1.0> To do so.

Yes you can parse an xml file which does not start with <?xml version = 1.0> . For eg

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());
}

will work. But your String xml file will not work. For xml parsers to work there should be a root tag and then all tags inside it. So

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

will not work but

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

will work. What you can do as a workaround for this is

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM