xml解析工具类

本文介绍了一个用于解析XML字符串的Java工具类,提供了从XML中提取节点值、属性值等功能,并通过示例展示了如何使用这些方法来解析包含不同层级的XML数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class XmlUtil {





private  DocumentBuilderFactory factory = null;
private  DocumentBuilder builder = null;


/**
*example, node string: <a> <b>1</b> <c>3</c> </a>,
* return the first node named $nodeName's value
* <P>
* if namespaceUri is null ,ignore it.

* @param node
* @param namespaceUri
* @param nodeName
* @return
*/
public  String getNodeValue(Node pNode, String namespaceUri,
String nodeName) {
return getNodeText(getSingleNode(pNode, namespaceUri, nodeName));
}


/**
* parse xml from xmlstring

* @param xmlString
* @param useNamespace
* @return
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public  Document parseFromString(String xmlString,
boolean useNamespace) throws ParserConfigurationException,
SAXException, IOException, Exception {
if (xmlString == null || xmlString.trim().length() == 0) {
throw new Exception("empty xml string.");
}
ByteArrayInputStream bais = new ByteArrayInputStream(xmlString
.getBytes());


return parse(bais, useNamespace);
}


public  Document parse(InputStream is, boolean useNamespace)
throws ParserConfigurationException, SAXException, IOException {
// if (factory == null) {
factory = DocumentBuilderFactory.newInstance();
// }
factory.setNamespaceAware(useNamespace);
// if (builder == null) {
builder = factory.newDocumentBuilder();
// }
Document dom = builder.parse(is);
return dom;
}

/**
* example, node string: &lt;a>2&lt;/a>,return "2";

* @param node
* @return
*/
public  String getNodeText(Node node) {


String s = null;
if (node == null) {
return null;
}
Node innerText = node.getFirstChild();
if (innerText != null && innerText.getNodeType() == Node.TEXT_NODE) {
s = innerText.getNodeValue();
}
// if innerText is null such as <a></a>, return ""
if (innerText == null) {
s = "";
}
return s;
}


/**
* example, node string: &lt;a> &lt;b>1&lt;/b> &lt;c>3&lt;/c> &lt;/a>,return
* that first node named $nodeName
* <P>
* if namespaceUri is null ,ignore it.

* @param parent
* @param namespaceUri
* @param nodeName
* @return
*/
public  Node getSingleNode(Node pNode, String namespaceUri,
String nodeName) {
NodeList nodelist = pNode.getChildNodes();
for (int i = 0; nodelist != null && i < nodelist.getLength(); i++) {
Node child = nodelist.item(i);

// Log.e("xmlutil--", "getLocalName:"+child.getLocalName()+"getNodeName:"+child.getNodeName()+"getNamespaceURI:"+child.getNamespaceURI());
if (namespaceUri != null) {
// namespace is not null, compare it
if (namespaceUri.equals(child.getNamespaceURI())
&& child.getLocalName().equals(nodeName))
return child;
} else {
if (child.getNodeName().equals(nodeName))
return child;
}
}
return null;
}


/**
* example, node string: &lt;a> &lt;b>1&lt;/b>
* &lt;b>2&lt;/b>&lt;b>3&lt;/b>&lt;/a>,return all nodes named $nodeName;
* <P>
* if namespaceUri is null ,ignore it.

* @param pNode
* @param namespaceUri
* @param nodeName
* @return
*/
public  List<Node> getNodeList(Node pNode, String namespaceUri,
String nodeName) {
NodeList nodelist = pNode.getChildNodes();
List<Node> nodesNeeds = new ArrayList<Node>();
for (int i = 0; nodelist != null && i < nodelist.getLength(); i++) {
Node child = nodelist.item(i);
if (namespaceUri != null) {
// namespace is not null, compare it
if (namespaceUri.equals(child.getNamespaceURI())
&& child.getLocalName().equals(nodeName)) {
nodesNeeds.add(child);
}
} else {
if (child.getNodeName().equals(nodeName)) {
nodesNeeds.add(child);
}
}
}
return nodesNeeds;
}


/**
* get first none text node.

* @param pNode
* @return
*/
public  Node getFirstNode(Node pNode) {
Node node = null;
NodeList nodelist = pNode.getChildNodes();
for (int i = 0; nodelist != null && i < nodelist.getLength(); i++) {
Node child = nodelist.item(i);
if (child.getNodeType() != Node.TEXT_NODE) {
node = child;
return node;
}
}
return node;
}


/**
* example, node string: &lt;a b="1"&gt;&lt;/a&gt;,if $nodeName="b",return
* "1";
* <P>
* if namespaceUri is null ,ignore it.

* @param node
* @param namespaceUri
* @param attName
* @return
*/
public  String getAttributeValue(Node node, String namespaceUri,
String attName) {
NamedNodeMap map = node.getAttributes();
if (namespaceUri == null) {
return map.getNamedItem(attName) == null ? null : map.getNamedItem(
attName).getNodeValue();
} else {
return map.getNamedItemNS(namespaceUri, attName) == null ? null
: map.getNamedItemNS(namespaceUri, attName).getNodeValue();
}
}

}


public static Msg parseFromString(String xmlString) throws Exception{
Msg msg=new Msg();
XmlUtil xmlUtil=new XmlUtil();
Document dom = null;
try{
dom = xmlUtil.parseFromString(xmlString, false);
Element root = dom.getDocumentElement();
//获取头信息
NodeList nodeList1=root.getElementsByTagName("HEAD");
if(nodeList1.getLength()>0){
Node head=nodeList1.item(0);
                msg.setID(xmlUtil.getNodeValue(head, null, "ID"));
                msg.setENCRYTION(xmlUtil.getNodeValue(head, null, "ENCRYTION"));
                msg.setLOGINNAME(xmlUtil.getNodeValue(head, null, "LOGINNAME"));
                msg.setPASSWORD(xmlUtil.getNodeValue(head, null, "PASSWORD"));
                msg.setSERIALNUM(xmlUtil.getNodeValue(head, null, "SERIALNUM"));
                msg.setSERVICEID(xmlUtil.getNodeValue(head, null, "SERVICEID"));
                msg.setTIMESTAMP(xmlUtil.getNodeValue(head, null, "TIMESTAMP"));
                msg.setVERSION(xmlUtil.getNodeValue(head, null, "VERSION"));
}
  List<Node> nodeList2=xmlUtil.getNodeList(root,null,"BODY");

  List<BODY> list=getBODY(nodeList2);
  msg.setBodylist(list);
  return msg;
}catch (Exception e) {
e.printStackTrace();
throw new Exception("parse message error.");
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值