纵有疾风起
人生不言弃

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;            }

 

文章转载于:https://www.cnblogs.com/lm970585581/p/7691140.html

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » jdom解析xml

分享到: 生成海报
avatar

评论 抢沙发

评论前必须登录!

立即登录   注册

切换注册

登录

忘记密码 ?

切换登录

注册

我们将发送一封验证邮件至你的邮箱, 请正确填写以完成账号注册和激活