对于带有表空间xmlns的xml文件的解析

对于带有表空间xmlns的xml文件的解析,用正常解析文件的方法总是失效,不起作用,无法获得元素。

下面给出两种方法解析此类文件:

1.按正常解析xml文件的方法,需要注意几点:

  • 获取元素Element,不可使用函数:document.selectNodes("//region");

只可以先取到根元素,一级一级往下取,eg:

Element root = document.getRootElement();

Element ele = root.element("head");

  • 获取属性值,可以按一般的方法操作,eg:

List ll = document.selectNodes("//@regionName");
  System.out.println("ll.size=" + ll.size());

2.使用XPath。eg:

public void testHasNameSpace(File file) { SAXReader saxReader = new SAXReader(); Document document = null; // XmlDocument document= try { document = saxReader.read(file); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } HashMap xmlMap = new HashMap(); xmlMap.put("smil", "http://www.w3.org/2000/SMIL20/CR/Language"); XPath x = document.createXPath("//smil:region"); x.setNamespaceURIs(xmlMap); List regionList = x.selectNodes(document); System.out.println("there are " + regionList.size() + " regions"); XPath att = document.createXPath("//smil:region/@regionName"); att.setNamespaceURIs(xmlMap); List attrList = att.selectNodes(document); System.out.println("there are " + attrList.size() + " attrs"); int i = 0; Iterator it = attrList.iterator(); while (it.hasNext()) { Attribute a = (Attribute) it.next(); System.out.println((i++) + "个:" + a.getValue()); } }

你可能感兴趣的:(xml,list,HashMap,File,iterator)