1.xml文档:
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<PhoneInfo>
<Brand name="华为">
<Type name="HW123" />
<Type name="HW321" />
</Brand>
<Brand name="iPhone">
<Type name="iPhone6" />
<Type name="iPhone5" />
<Type name="iPhone4S" />
</Brand>
</PhoneInfo>
2.测试类:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DOMTest {
public static void main(String[] args) throws Exception {
// 1.得到DOM解析器的工厂实例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 2.从DOM工厂得到DOM解析器
DocumentBuilder db = dbf.newDocumentBuilder();
// 3.解析XML文档,得到DOM树
Document doc = db.parse("src/收藏信息.xml");
//4.得到所有<Brand>的子节点
NodeList list=doc.getElementsByTagName("Brand");
//5.循环Brand信息
for (int i = 0; i < list.getLength(); i++) {
Node brandNode=list.item(i);
Element brandElement=(Element) brandNode;
String brandName=brandElement.getAttribute("name");
//获取子节点
NodeList childList=brandNode.getChildNodes();//注:获取ChildNodes时xml不能有空格
for(int j=0;j<childList.getLength();j++){
Element typeElement=(Element)childList.item(j);
String typeName=typeElement.getAttribute("name");//getNodeValue()获取节点的文本值
System.out.println("手机:"+brandName+"---"+typeName);
}
}
/*添加节点*/
//创建brand节点
Element brandElement =doc.createElement("Brand");
brandElement.setAttribute("name", "HTC");
//创建type节点
Element typeEle=doc.createElement("type");
typeEle.setAttribute("name", "G11");
//添加关系(父节点添加子节点)
brandElement.appendChild(typeEle);
Element root=(Element) doc.getElementsByTagName("PhoneInfo").item(0);
root.appendChild(brandElement);
//xml进行更新处理
TransformerFactory tf=TransformerFactory.newInstance();
Transformer transformer=tf.newTransformer();
DOMSource domSource=new DOMSource(doc);
transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");//设置编码
StreamResult result=new StreamResult(new FileOutputStream("src/收藏信息.xml"));
//把DOM树转换为xml文档
transformer.transform(domSource, result);
}
}