读取xml:
读取单个节点:
读取单个节点list:
每一层节点都可以用[@属性key='属性值']的形式传入属性参数来读取。
从指定node取得属性:
从节点list取得标签内text内容:
Document document = XmlUtil.getDocument( filePath );
public static Document getDocument( String filePath ) throws ParserConfigurationException, SAXException,
IOException {
// 需要添加判断参数为空操作
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder = factory.newDocumentBuilder();
return builder.parse( new File( filePath ) );
}
读取单个节点:
public static Node getSingleNode( Node contextNode, String xPath ) throws TransformerException,
XPathExpressionException {
// 需要添加判断参数为空操作
XPathFactory factory = XPathFactory.newInstance();
XPath path = factory.newXPath();
NodeList nodeList = (NodeList) path.evaluate( xPath, contextNode, XPathConstants.NODESET );
return nodeList.item( 0 );
}
读取单个节点list:
NodeList groupingList = XmlUtil.getNodeList( document, "//xml根节点/page[@id='" + pageNo+ "']/grouping" );
每一层节点都可以用[@属性key='属性值']的形式传入属性参数来读取。
public static NodeList getNodeList( Node contextNode, String xPath ) throws XPathExpressionException,
ParserConfigurationException, SAXException, IOException, TransformerException {
// 需要添加判断参数为空操作
XPathFactory factory = XPathFactory.newInstance();
XPath path = factory.newXPath();
NodeList nodeList = (NodeList) path.evaluate( xPath, contextNode, XPathConstants.NODESET );
return nodeList;
}
从指定node取得属性:
Node rowNode = nodeList.item( i );
String rowNo = XmlUtil.getAttribute( rowNode, "row" );
public static String getAttribute( Node contextNode, String attributeName ) {
// 需要添加判断参数为空操作
String target = attributeName.toUpperCase();
NamedNodeMap attributes = contextNode.getAttributes();
for ( int i = 0; i < attributes.getLength(); i++ ) {
if ( target.equals( attributes.item( i ).getNodeName().toUpperCase() ) ) {
return attributes.item( i ).getNodeValue();
}
}
return null;
}
从节点list取得标签内text内容:
public static String getTextContentsByName( NodeList nodeList, String nodeName ) {
// 需要添加判断参数为空操作
String textContents = StringUtil.EMPTY;
for ( int i = 0; i < nodeList.getLength(); i++ ) {
Node node = nodeList.item( i );
if ( node.getNodeName().equals( nodeName ) ) {
textContents = node.getTextContent();
break;
}
}
return textContents;
}