繁体   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