jdom解析xml

jdom当然要引入jdom的jar包了。

没有多余的废话,直接看解析代码:

例子1:读取本地xml文件并修改后保存为另一个xml文件

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class JDomTest2
{
 public static void main(String[] args) throws Exception
 {
  //JDOM从XML中解析
  SAXBuilder builder = new SAXBuilder();
  //获得XML文档对象
  Document doc = builder.build(new File("jdom.xml"));
  //得到文档根元素
  Element element = doc.getRootElement();
  
  System.out.println(element.getName());
  //得到根元素下的hello元素
  Element hello = element.getChild("hello");
  
  System.out.println(hello.getText());
  //得到hello子元素下的属性
  List list = hello.getAttributes();
  
  //得到hello元素下属性的名字和值
  for(int i = 0 ;i < list.size(); i++)
  {
   Attribute attr = (Attribute)list.get(i);
   
   String attrName = attr.getName();
   String attrValue = attr.getValue();
   
   System.out.println(attrName + "=" + attrValue);
  }
  //删除hello下的world子元素
  hello.removeChild("world");
  
  //将文档保存到另一个文件
  XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
  
  out.output(doc, new FileOutputStream("jdom2.xml"));  
  
 }
}

 例子2:获取webservice的参数,并通过xpath准确定位数据,且xml中有namespace(项目中常用)

public Map<String, Object> getNJXml(String xmlStr) throws JDOMException, IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        //解析
        StringReader xmlReader=new StringReader(xmlStr);
        SAXBuilder bulider = new SAXBuilder();
        Document document = bulider.build(xmlReader);
        Element element = document.getRootElement();
        Namespace ns=element.getNamespace();
        Element order = element.getChild("inFulfillmentOf",ns).getChild("order",ns);
        XPath xpath = getXpath("ns:id[@root='1.2.156.112722.1.2.1.20']");
        Element id = (Element) xpath.selectSingleNode(order);
        String flow = id.getAttributeValue("extension");
        map.put("flow", flow);
        xpath=getXpath("ns:component[4]");
        Element structuredBody = element.getChild("component",ns).getChild("structuredBody",ns);
        Element component =(Element) xpath.selectSingleNode(structuredBody);
        String checkCont = component.getChild("section",ns).getChildText("text",ns);
        map.put("checkCont", checkCont);
     return map; }
private XPath getXpath(String expression) throws JDOMException{
        XPath xpath=XPath.newInstance(expression);
        xpath.addNamespace("ns", "urn:hl7-org:v3");
        return xpath;
        
    }

 

posted @ 2017-10-19 10:35  H.U.C-王子  阅读(257)  评论(0编辑  收藏  举报