欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java操作xml - dom4j

程序员文章站 2022-05-28 20:27:46
...

本文通过实现将一个XML中的所有id值由正数更新为负值为例,展示dom4j读取、遍历以及更新xml的操作。

一、样例说明:

以下xml中的id="-182655332",<tag k="id" v="-182655332"/>,<member type="Highway" role="road" ref="-159475967"/>,<nd ref="-1262293804"/>都是我们要操作的数据(由正数改为负数)。

<?xml version="1.0" encoding="utf-8"?>
<osmChange>
  <topoGroup>
    <create>
      <way id="-182655332" version="1" transactionLoc="POINT (112.85030896500966 28.385729770656106)" changeset="20013309">
        <tag k="changeset_id" v="20013309"/>
        <tag k="visible" v="t"/>
        <tag k="area_flag" v="0"/>
        <tag k="adcode"/
        <tag k="source"/>
        <tag k="version" v="1"/>
        <tag k="src_flag" v="0"/>
        <tag k="datatype" v="DetailSlope"/>
        <tag k="id" v="-182655332"/>
        <tag k="mesh" v="H49F044039"/>
        <tag k="timestamp" v="1535361977065"/>
        <tag k="reference" v="{&quot;all&quot;:&quot;4081898_3_6f286966b604472994c0a91a160a4e51&quot;}"/>
      </way>
      <relation id="-19585073" lat="28.38493004" lon="112.84922079500001" version="1" transactionLoc="POINT (112.84922079500001 28.38493004)" changeset="20013309">
        <member type="Highway" role="road" ref="-159475967"/>
        <member type="DetailSlope" role="ds" ref="-182655332"/>
        <tag k="changeset_id" v="20013309"/>
        <tag k="visible" v="t"/>
        <tag k="datatype" v="RelDetailSlope"/>
        <tag k="adcode"/>
        <tag k="id" v="-19585073"/>
        <tag k="version" v="1"/>
        <tag k="mesh" v="H49F044039"/>
        <tag k="timestamp" v="1535361977065"/>
        <tag k="reference" v="{&quot;all&quot;:&quot;4081898_3_6f286966b604472994c0a91a160a4e51&quot;}"/>
      </relation>
    </create>
    <modify/>
    <delete/>
  </topoGroup>
  <create>
    <way id="-159475967" version="2" transactionLoc="POINT (112.84922079500001 28.38493004)" changeset="20013309" operType="3">
        <nd ref="-1262293804"/>
        <nd ref="-1262293805"/>
        <tag k="slope_src" v="2"/>
        <tag k="updatetime" v="20180827172617"/>
        <tag k="verifytime" v="20180707162959"/>
        <tag k="updateuser" v="2"/>
        <tag k="id" v="-159475967"/>
        <tag k="datatype" v="Highway"/>
        <tag k="the_geom" v="LINESTRING (112.84837322 28.38593057, 112.85006837 28.38392951)"/>
        <tag k="reference" v="{&quot;all&quot;:&quot;4081898_3_6f286966b604472994c0a91a160a4e51&quot;}"/>
    </way>
  </create>
  <modify/>
  <delete/>
</osmChange>
二、代码实现
//处理XML, 将xml中所有id值由正数更新为负值
public String processDeltaXML(String mark_delta_xml) {
    //遍历delta xml
    Document document = getDocument(mark_delta_xml);
    Element rootElement = document.getRootElement();
    handleDeltaXML(rootElement);
    return document.asXML();
}

//读取xml串转换成xml对象
private Document getDocument(String xmlContent) {
Document docDeltaXml = null;
try {
    SAXReader reader = new SAXReader();
    reader.setEncoding("GBK");
    docDeltaXml = reader.read(new ByteArrayInputStream(xmlContent
            .getBytes("GBK")));
} catch (Exception e) {
    System.out.println("解析xml失败");
    e.printStackTrace();
}
    return docDeltaXml;
}

//循环遍历xml进行处理
private void handleDeltaXML(Element rootElement) {
   Map<String, List<Element>> operateElementList = new HashMap<>();
   getOperateElementMap(rootElement, operateElementList);

   Set<Map.Entry<String, List<Element>>> entrySet = operateElementList.entrySet();
   Iterator<Map.Entry<String, List<Element>>> iter = entrySet.iterator();
   while (iter.hasNext()){
       Map.Entry<String, List<Element>> entry = iter.next();
       if ("create".equals(entry.getKey())) {
           handleOperateElements_create(entry.getValue());
       }
   }
}

// 解析xml对象获取到element name为"create", "modify","delete"的子结点
private void getOperateElementMap(Element rootElement, Map<String, List<Element>> operateElementMap) {
    List<String> operNames = new ArrayList<String>(){
        {
            add("create");
            add("modify");
            add("delete");
        }
    };

    List<Element> rootElementsList = rootElement.elements();
    for (Element element : rootElementsList) {
        if (operNames.contains(element.getName())) {
            if (operateElementMap.containsKey(element.getName())) {
                operateElementMap.get(element.getName()).addAll(element.elements());
            }
            else
            {
                operateElementMap.put(element.getName(), new ArrayList<>(element.elements()));
            }
        }
        else
        {
            getOperateElementMap(element, operateElementMap);
        }
    }
}

//处理新增结点
private void handleOperateElements_create(List<Element> createElementList) {
    for (Element element : createElementList) {
        //修改element上的id属性
        Attribute attr_id = element.attribute("id");
        attr_id.setValue("-" + attr_id.getValue());

        for (Object element_tag : element.elements()) {
            //修改非tag结点的ref属性
            if (!"tag".equals(((Element) element_tag).getName())) {
                Attribute attr_member_ref = ((Element) element_tag).attribute("ref");
                attr_member_ref.setValue("-" + attr_member_ref.getValue());
            }
            //修改tag为id结点的v属性
            else
            {
                if ("id".equals(((Element) element_tag).attributeValue("k"))) {
                    Attribute attr_tag_id = ((Element) element_tag).attribute("v");
                    attr_tag_id.setValue("-" + attr_tag_id.getValue());
                }
            }
        }

        //修改tag为id结点的v属性
        //Attribute attr_tag_id = ((Element) element.selectObject("tag[@k='id']")).attribute("v");
        //attr_tag_id.setValue("-" + attr_tag_id.getValue());

    }
}
相关标签: xml dom4j