Dom4j使用示例

Dom4j 是一个易用的、开源的库,用于 XML , XPath 和 XSLT 。它应用于 Java 平台,采用了 Java 集合框架并完全支持 DOM , SAX 和 JAXP 。
 
要使用dom4j读写XML文档,需要先下载dom4j包
下载dom4j-1.6.1.zip
解开后有两个包,仅操作XML文档的话把dom4j-1.6.1.jar加入工程就可以了,如果需要使用XPath的话还需要加入包jaxen-1.1-beta-7.jar
先上xml文件
<?xml version="1.0" encoding="UTF-8"?>
<mxGraphModel>
	<root>
		<mxCell id="0" />
		<mxCell id="1" parent="0" />
		<mxCell id="2" parent="1" vertex="1">
			<Activity4Graph as="value" isLeaf="Y" name="活动1"
				state="C" />
			<mxGeometry as="geometry" height="70.0" width="100.0" x="290.0"
				y="90.0" />
		</mxCell>
		<mxCell id="3" parent="1" vertex="1">
			<Activity4Graph AId="7efcc9a6-9d7e-11df-9842-1d6abb6dee61"
				as="value" isLeaf="N" name="活动2" state="C" />
			<mxGeometry as="geometry" height="70.0" width="100.0" x="40.0"
				y="190.0" />
		</mxCell>
		<mxCell edge="1" id="4" parent="1" source="2" style="" target="3">
			<ActivityRelation4Graph as="value" name="连线3" />
			<mxGeometry as="geometry" relative="1">
				<mxPoint as="sourcePoint" x="360.0" y="145.0" />
				<mxPoint as="targetPoint" x="140.0" y="260.0" />
			</mxGeometry>
		</mxCell>
		<mxCell id="5" parent="1" vertex="1">
			<Activity4Graph AId="936d24de-9dd9-11df-9842-1d6abb6dee61"
				as="value" isLeaf="N" name="活动4" state="C" />
			<mxGeometry as="geometry" height="70.0" width="100.0" x="270.0"
				y="340.0" />
		</mxCell>
		<mxCell edge="1" id="6" parent="1" source="3" style="" target="5">
			<ActivityRelation4Graph as="value" name="连线5" />
			<mxGeometry as="geometry" relative="1">
				<mxPoint as="sourcePoint" x="130.0" y="255.0" />
				<mxPoint as="targetPoint" x="360.0" y="380.0" />
			</mxGeometry>
		</mxCell>
		<mxCell id="7" parent="1" vertex="1">
			<Activity4Graph as="value" isLeaf="Y" name="活动6"
				state="C" />
			<mxGeometry as="geometry" height="70.0" width="100.0" x="510.0"
				y="260.0" />
		</mxCell>
		<mxCell edge="1" id="8" parent="1" source="5" style="" target="7">
			<ActivityRelation4Graph as="value" name="连线7" />
			<mxGeometry as="geometry" relative="1">
				<mxPoint as="sourcePoint" x="350.0" y="385.0" />
				<mxPoint as="targetPoint" x="580.0" y="330.0" />
			</mxGeometry>
		</mxCell>
		<mxCell id="9" parent="1" vertex="1">
			<Activity4Graph as="value" isLeaf="Y" name="活动8"
				state="C" />
			<mxGeometry as="geometry" height="70.0" width="100.0" x="490.0"
				y="60.0" />
		</mxCell>
		<mxCell edge="1" id="10" parent="1" source="2" style="" target="9">
			<ActivityRelation4Graph as="value" name="连线9" />
			<mxGeometry as="geometry" relative="1">
				<mxPoint as="sourcePoint" x="360.0" y="145.0" />
				<mxPoint as="targetPoint" x="540.0" y="90.0" />
			</mxGeometry>
		</mxCell>
		<mxCell id="A:3:R.12" parent="1" style="fillColor=#FFFFCC"
			vertex="1">
			<AARole4Graph aarID="9b8831d2-9d7e-11df-9842-1d6abb6dee61"
				as="value" name="521_wa_5:wr1" />
			<mxGeometry as="geometry" height="30.0" width="100.0" x="40.0"
				y="260.0" />
		</mxCell>
		<mxCell id="A:3:I.13" parent="1" style="fillColor=#00FFCC"
			vertex="1">
			<Indicator4Graph as="value" graphID="A:3:I.13"
				indicatorID="a1eb3199-9d7e-11df-9842-1d6abb6dee61" name="业务指标11" />
			<mxGeometry as="geometry" height="10.0" width="10.0" x="40.0"
				y="180.0">
				<mxPoint as="offset" x="50.0" />
			</mxGeometry>
		</mxCell>
		<mxCell id="11" parent="1" vertex="1">
			<Activity4Graph as="value" isLeaf="Y" name="活动1"
				state="C" />
			<mxGeometry as="geometry" height="70.0" width="100.0" />
		</mxCell>
	</root>
</mxGraphModel>
 解析代码
  
public class ReadXML {

	public static Map<String, Location> maps;
	static {
		maps = new HashMap<String, Location>();
	}

	public static void main(String[] args) {
		readXML("xml/demo.xml");
	}

	public static Map<String, Location> readXML(String path) {
		 Map<String, Location> mms= new HashMap<String, Location>();
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(loadResource(path));
			List<Element> eleList = doc
					.selectNodes("/mxGraphModel/root/mxCell");
			for (Element ele : eleList) {
				// String id = ele.valueOf("@id");
				Location loc = new Location();
				List<Element> Activity4Graphs = ele.elements("Activity4Graph");// 获取某节点下指定节点
				int size = DataOptUtil.getSize(Activity4Graphs);
				if (size > 0) {
					for (Element element : Activity4Graphs) {
						String name = element.valueOf("@name");
						if (DataOptUtil.isNotNull(name)) {
							loc.setNodeName(name);
						}
					}
				}

				List<Element> Indicator4Graphs = ele
						.elements("Indicator4Graph");// 获取某节点下指定节点
				int size1 = DataOptUtil.getSize(Indicator4Graphs);
				if (size1 > 0) {
					for (Element element : Indicator4Graphs) {
						String name = element.valueOf("@name");
						if (DataOptUtil.isNotNull(name)) {
							loc.setNodeName(name);
						}

					}
				}

				List<Element> AARole4Graphs = ele.elements("AARole4Graph");// 获取某节点下指定节点
				int size2 = DataOptUtil.getSize(AARole4Graphs);
				if (size2 > 0) {
					for (Element element : AARole4Graphs) {
						String name = element.valueOf("@name");
						if (DataOptUtil.isNotNull(name)) {
							loc.setNodeName(name);
						}
					}
				}

				List<Element> ActivityRelation4Graphs = ele
						.elements("ActivityRelation4Graph");// 获取某节点下指定节点
				int size3 = DataOptUtil.getSize(ActivityRelation4Graphs);
				if (size3 > 0) {
					for (Element element : ActivityRelation4Graphs) {
						String name = element.valueOf("@name");
						if (DataOptUtil.isNotNull(name)) {
							loc.setNodeName(name);
						}
					}
				}

				List<Element> mxGeometryS = ele.elements("mxGeometry");
				for (Element element : mxGeometryS) {

					if (DataOptUtil.isNotNull(element.valueOf("@width"))) {
						double width = Double
								.valueOf(element.valueOf("@width"));
						loc.setWidth(width);
					}
					if (DataOptUtil.isNotNull(element.valueOf("@height"))) {
						double height = Double.valueOf(element
								.valueOf("@height"));
						loc.setHeight(height);
					}
					if (DataOptUtil.isNotNull(element.valueOf("@x"))) {
						double x = Double.valueOf(element.valueOf("@x"));
						loc.setValueX(x);
					}
					if (DataOptUtil.isNotNull(element.valueOf("@y"))) {
						double y = Double.valueOf(element.valueOf("@y"));
						loc.setValueY(y);
					}

					List<Element> mxPoints = element.elements("mxPoint");// 获取某节点下指定节点
					int size4 = DataOptUtil.getSize(mxPoints);
					if (size4 > 0) {
						for (Element e : mxPoints) {
							if (DataOptUtil.isNotNull(e.valueOf("@x"))) {
								double x = Double.valueOf(e.valueOf("@x"));
								loc.setValueX(x);
							}
							if (DataOptUtil.isNotNull(e.valueOf("@y"))) {
								double y = Double.valueOf(e.valueOf("@y"));
								loc.setValueY(y);
							}

						}

					}
				}
				if (loc.getNodeName()!=null) {
					//System.out.println(loc);
					mms.put(loc.getNodeName(), loc);
				}
			}
			for (Entry<String, Location> entry : maps.entrySet()) {
				System.out.println(entry.getKey() + "===" + entry.getValue());
			}
			
			

		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return mms;
	}

	public static InputStream loadResource(String path) {
		return Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(path);
	}
}
 涉及到的Location类
  
public class Location {
	private String nodeName;
	private double width;
	private double height;
	private double valueX;
	private double valueY;

	
	

	public String getNodeName() {
		return nodeName;
	}

	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}

	public double getWidth() {
		return width;
	}

	public void setWidth(double width) {
		this.width = width;
	}

	public double getHeight() {
		return height;
	}

	public void setHeight(double height) {
		this.height = height;
	}

	public double getValueX() {
		return valueX;
	}

	public void setValueX(double valueX) {
		this.valueX = valueX;
	}

	public double getValueY() {
		return valueY;
	}

	public void setValueY(double valueY) {
		this.valueY = valueY;
	}

	@Override
	public String toString() {
		return "Location [height=" + height + ", nodeName=" + nodeName + ", valueX="
				+ valueX + ", valueY=" + valueY + ", width=" + width + "]";
	}

	
}
 
接下来进行dom4j的详细介绍
  
以下是相关操作:
一.Document对象相关
1.读取XML文件,获得document对象.
            SAXReader reader = new SAXReader();
            Document  document = reader.read(new File("input.xml"));
2.解析XML形式的文本,得到document对象.
            String text = "<members></members>";
            Document document = DocumentHelper.parseText(text);
3.主动创建document对象.
            Document document = DocumentHelper.createDocument();
            Element root = document.addElement("members");// 创建根节点

二.节点相关
1.获取文档的根节点.
Element rootElm = document.getRootElement();
2.取得某节点的单个子节点.
Element memberElm=root.element("member");// "member"是节点名
3.取得节点的文字
String text=memberElm.getText();
也可以用:
String text=root.elementText("name");这个是取得根节点下的name字节点的文字.
 
4.取得某节点下名为"member"的所有字节点并进行遍历.
List nodes = rootElm.elements("member");
for (Iterator it = nodes.iterator(); it.hasNext();) {
   Element elm = (Element) it.next();
   // do something
}
5.对某节点下的所有子节点进行遍历.
            for(Iterator it=root.elementIterator();it.hasNext();){
                Element element = (Element) it.next();
                // do something
            }
6.在某节点下添加子节点.
Element ageElm = newMemberElm.addElement("age");
7.设置节点文字.
ageElm.setText("29");
8.删除某节点.
parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点
 
获取一个Element之后可以进行的相关操作:
attributue(String name) :获取元素String值。
elementIterator() :返回元素的所有子元素的Iterator迭代器。
elements() :返回元素包含所有子元素List。
getParent() :获取父元素Element。
getPath() :获取自己的xpath。
detach() :移除自己。
getName() :获取节点的名称。
selectNodes(String xpathExpression) :通过XPATH获取节点。
selectSingleNode(String xpathExpression) :通过XPATH获取一个节点。
getDocument() :作为一个Document返回。

三.属性相关
1.取得某节点下的某属性
            Element root=document.getRootElement();   
            Attribute attribute=root.attribute("size");// 属性名name

2.取得属性的文字
            String text=attribute.getText();
也可以用:
String text2=root.element("name").attributue("firstname");这个是取得根节点下name字节点的属性firstname的值.
 
3.遍历某节点的所有属性
            Element root=document.getRootElement();   
            for(Iterator it=root.attributeIterator();it.hasNext();){
                Attribute attribute = (Attribute) it.next();
                String text=attribute.getText();
                System.out.println(text);
            }

4.设置某节点的属性和文字.
newMemberElm.addAttribute("name", "sitinspring");

5.设置属性的文字
            Attribute attribute=root.attribute("name");
            attribute.setText("sitinspring");

6.删除某属性
            Attribute attribute=root.attribute("size");// 属性名name
            root.remove(attribute);

四.将文档写入XML文件
1.文档中全为英文,不设置编码,直接写入的形式.
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(document);
writer.close();

2.文档中含有中文,设置编码格式写入的形式.
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("GBK");    // 指定XML编码       
            XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);
           
            writer.write(document);
            writer.close();

五.字符串与XML的转换
1.将字符串转化为XML
String text = "<members> <member>sitinspring</member> </members>";
Document document = DocumentHelper.parseText(text);

2.将文档或节点的XML转化为字符串.
            SAXReader reader = new SAXReader();
            Document  document = reader.read(new File("input.xml"));           
            Element root=document.getRootElement();               
            String docXmlText=document.asXML();
            String rootXmlText=root.asXML();
            Element memberElm=root.element("member");
            String memberXmlText=memberElm.asXML();

六.使用XPath快速找到节点
读取的XML文档示例
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
  <name>MemberManagement</name>
  <comment></comment>
  <projects>
    <project>PRJ1</project>
    <project>PRJ2</project>
    <project>PRJ3</project>
    <project>PRJ4</project>
  </projects>
  <buildSpec>
    <buildCommand>
      <name>org.eclipse.jdt.core.javabuilder</name>
      <arguments>
      </arguments>
    </buildCommand>
  </buildSpec>
  <natures>
    <nature>org.eclipse.jdt.core.javanature</nature>
  </natures>
</projectDescription>
使用XPath快速找到节点project.
 public static void main(String[] args){
    SAXReader reader = new SAXReader();
   
    try{
      Document  doc = reader.read(new File("sample.xml"));
      List projects=doc.selectNodes("/projectDescription/projects/project");
      Iterator it=projects.iterator();
      while(it.hasNext()){
        Element elm=(Element)it.next();      
        System.out.println(elm.getText());
      }
     
    }
    catch(Exception ex){
       ex.printStackTrace();
    }
  }

你可能感兴趣的:(eclipse,c,xml,活动,360)