简体   繁体   中英

What is the best way to parse a xml file without xmlns?

For reason beyond my control, I must parse a xml without xmlns tag. I believe that it is a bad practice because it miss namespace control. Anyway, I must program for such scenario. What could be the best way to face it? I try setNamespaceAware = false and it does work for file without xmlns tag but it seems that it doesn't work properly when reading xml with xmlns tag. Plus this, I guess that by setting any awareness configuration to false isn't a good practice. I read some article telling to add the xmlns to the file programmatically but I am in doubt if it might be a good option. Any comment will be appreciated.

javax.xml.parsers.DocumentBuilderFactory fac = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
fac.setNamespaceAware(true);
org.w3c.dom.Document d = null;
javax.xml.parsers.DocumentBuilder builder = fac.newDocumentBuilder();
d = builder.parse("C:/my_folder/my_file.xml");


<?xml version="1.0" encoding="UTF-8"?>
<c:de format="N" lengthField="0" maxLength="012" minLength="012" name="AMOUNT, TRANSACTION" number="004" subFields="00"/>

如果可以为文件创建模式,请创建该模式(不使用targetNamespace属性,这意味着目标名称空间为“”),生成类(例如,使用xjc / JAXB)并进行解析。

Here are the statements that I use to parse a XML file

DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(false);
dfactory.setValidating(false);
DocumentBuilder bldr = dfactory.newDocumentBuilder();
bldr.setErrorHandler(new ErrorHandler() {
    public void warning(SAXParseException exception) throws SAXException {
        // ignore warnings
    }

    public void error(SAXParseException exception) throws SAXException {
            // ignore parse validation errors
    }

    public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
    }
});
Document doc = bldr.parse(new InputSource(is));

I think you need to turn validation off if you turn namespace off.

There really is nothing wrong with using XML this way. Namespace help with a specific kind of evolution of the schema, but not all kinds, and if you analyze it far enough, namespace only delays the problem, but does not actually solve the problem. It depends on the specific XML, and some are managed in a way that requires the name space. But have no guilt if the XML is not managed this way.

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