SelectNodes("//item")
从任意位置的节点上选择名称为 item 的节点,即整个xml文件的所有名为item的节点。
dom4j.jar
文章是使用dom4j.jar去解析XML文件,如何下载可以自行百度。
代码
import部分(包括不限于)
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
function1
这个function是解析得到item节点是带Root节点名字空间的。依赖下面的function2
/**
* Get all target element with root element's name space from XML file
*
* @param xmlFile need to parse
* @param targetElement target element name
* @return all target element
* @throws DocumentException document exception
*/
public static List<Element> getAllTargetElementListWithNameSpaceFromXmlFile(File xmlFile, String targetElement) throws DocumentException {
SAXReader xmlReader = new SAXReader();
String nameSpace = null;
try {
Document doc = xmlReader.read(xmlFile);
nameSpace = doc.getRootElement().getNamespaceURI();
} catch (DocumentException e) {
e.printStackTrace();
throw e;
}
return getAllTargetElementListWithNameSpaceFromXmlFile(xmlFile, targetElement, nameSpace);
}
function2
这个function是解析得到item节点带名字空间。
/**
* Get all target element with name space from XML file
*
* @param xmlFile need to parse
* @param targetElement target element name
* @param nameSpace name space
* @return all target element
* @throws DocumentException document exception
*
*/
public static List<Element> getAllTargetElementListWithNameSpaceFromXmlFile(File xmlFile, String targetElement, String nameSpace) throws DocumentException {
List<Element> targetElementList = new ArrayList<>();
SAXReader xmlReader = new SAXReader();
Document doc = null;
try {
doc = xmlReader.read(xmlFile);
} catch (DocumentException e) {
e.printStackTrace();
throw e;
}
Map<String,String> map = new HashMap<>();
map.put("xmlns", nameSpace);
XPath x = (XPath) doc.createXPath("//xmlns:" + targetElement);
x.setNamespaceURIs(map);
for(Object obj : x.selectNodes(doc)) {
targetElementList.add((org.dom4j.Element) obj);
}
return targetElementList;
}
function3
这个function是解析得到没有名字空间的item
/**
* Get all target element without name space from XML file
*
* @param xmlFile need to parse
* @param targetElement target element name
* @return all target element
* @throws DocumentException document exception
*
*/
public static List<Element> getAllTargetNodeElementListWithoutNameSpaceFromXmlFile(File xmlFile, String targetElement) throws DocumentException {
List<Element> targetNodeElementList = new ArrayList<>();
SAXReader xmlReader = new SAXReader();
try {
Document doc = xmlReader.read(xmlFile);
for (Object obj : doc.selectNodes("//" + targetElement)) {
targetNodeElementList.add((org.dom4j.Element) obj);
}
} catch (DocumentException e) {
e.printStackTrace();
throw e;
}
return targetNodeElementList;
}