Java利用JDom来解析处理XML数据格式:node
须要的包jdom-1.1.2.jar服务器
1 将数据转换成XML格式的数据进行传递dom
Element rootList, firstList, secondItem, thirdItem;ide
//根元素标签名ui
rootList = new Element("root");xml
//根元素标签内的属性名与值对象
rootList.setAttribute("project", pname);ip
//生成Doc文档文档
Document Doc = new Document(rootList);字符串
//获取文档中的根标签
rootList = Doc.getRootElement();
for (int i = 0; i < judges.size(); i++)
{
//生成新的元素
firstList = new Element("flayout");
firstList.setAttribute("percent", "percent");
//加入根级元素中
rootList.addContent(firstList);
}
XMLOutputter XMLOut = new XMLOutputter();
//将doc文档转换为字符串型的XML格式
String xmlinfo = XMLOut.outputString(Doc);
//将开头的去掉
xmlinfo = xmlinfo.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"");
//返回已经封装好的XML数据
return xmlinfo;
2 将字符串中的XML解析出进行处理
//建立一个新的字符串
StringReader read = new StringReader(stadXML);
// 建立新的输入源SAX 解析器将使用 InputSource 对象来肯定如何读取 XML 输入
InputSource source = new InputSource(read);
// 建立一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
String projectName;
List<Judgestandard> standIndex = new ArrayList<Judgestandard>();
try {
// 经过输入源构造一个Document
Document doc = sb.build(source);
// 取的根元素
Element root = doc.getRootElement();
projectName = root.getAttributeValue("project");
// 获得根元素全部子元素的集合
Element et = null;
List nodes = root.getChildren();
// 第一级指标
for (int i = 0; i < nodes.size(); i++) {
et = (Element) nodes.get(i);// 循环依次获得子元素
Judgestandard judge = new Judgestandard();
//获取该元素中属性的值
String fid = et.getAttributeValue("mainid");
//获取元素的孩子数目
List fsize = et.getChildren();
// 第二级指标
for (int j = 0; j < fsize.size(); j++)
{
et = (Element) fsize.get(j);// 循环依次获得子元素
et.getAttributeValue("stdid")
}
Java处理XML文档
不须要包
待处理的XML文档:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<ip>localhost</ip>
<port>8080</port>
</root>
static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
static DocumentBuilder builder = null;
builder = factory .newDocumentBuilder();
//获取服务器根目录地址
Document document = builder.parse(new File("src/ip.xml"));
Element rootElement = document.getDocumentElement();
NodeList list1 = rootElement.getElementsByTagName("ip");
NodeList list2 = rootElement.getElementsByTagName("port");
Element ip = (Element) list1.item(0);
Element port = (Element) list2.item(0);
String s =ip.getFirstChild()。getNodeValue()。toString()+":"+port.getFirstChild()。getNodeValue()。toString();
System.out.println(s);