当前位置 : 主页 > 编程语言 > c++ >

java代码 xml 解析(不依赖其他)

来源:互联网 收集:自由互联 发布时间:2021-07-03
gistfile1.txt public class Test {public static void main(String[] args) { //XML 文件String result=" \r\n" + " \r\n" + " 后勤服务高级主管 \r\n" + " 后勤服务高级主管 \r\n" + " \r\n" + " 0 \r\n" + " \r\n" + " ";Document doc =
gistfile1.txt
public class Test {
	
	public static void main(String[] args) {
	   //XML 文件
		String result="
 
  \r\n" + 
				"  
  \r\n" + 
				"    
  
   后勤服务高级主管
  \r\n" + 
				"    
  
   后勤服务高级主管
  \r\n" + 
				"  \r\n" + 
				"  
  
   0
  \r\n" + 
				"  \r\n" + 
				"
 ";
	
	Document doc = ParseDom(result);              //解析dom
	NodeList nodelist = doc.getElementsByTagName("Title");  //获取title标签的节点
	System.out.println(nodelist.getLength());
		Node childNode = nodelist.item(0);
		if (childNode instanceof Element) {
			if(((Element) childNode).getElementsByTagName("TitleName").item(0)!=null){
			  
			   String title = ((Element) childNode).getElementsByTagName("TitleName")				  
					 .item(0).getTextContent();
			   System.out.println(title);  //打印titlename的值
		    }
          }
	}
	
    //解析xml
public static Document ParseDom(String sXML) {

	Document doc = null;
	try {
		String regex = "&(.*);";
		sXML = sXML.replaceAll(regex, "");
		StringReader sr = new StringReader(sXML);
		InputSource is = new InputSource(sr);
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		doc = builder.parse(is);

	} catch (SAXParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();

	} catch (ParserConfigurationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();

	} catch (SAXException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return doc;
}

//解析xml
private void buildFromHeadOrganization(String result,boolean isDupCheck) throws Exception {
		Document doc = ParseDom(result);
		NodeList resResult = doc.getElementsByTagName("Result");  //获取节点 result
		Node resultNode = resResult.item(0);
		String success = resultNode.getTextContent();  
		if (Integer.parseInt(success) < 0) {
			NodeList errInfo = doc.getElementsByTagName("ErrorDescription");
			Node errNode = errInfo.item(0);
			String info = errNode.getTextContent();
			log.error(info);
			return;
		}
		NodeList nodelist = doc.getElementsByTagName("Org");  //获取doc下的Org结点

		for (int j = 0; j < nodelist.getLength(); j++) {
			Node childNode = nodelist.item(j);
			if (childNode instanceof Element) {
				String rootOrgId = ((Element) childNode).getElementsByTagName(
						"OrgID").item(0).getTextContent();     //取到标签的值
				String rootOrgName = ((Element) childNode)
						.getElementsByTagName("OrgName").item(0)
						.getTextContent(); //获取值
			}
		}
	}
}
网友评论