xml的读取(sax)

读取xml:


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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值