求救:如何使用dom读取xml文档中的数据 http://www.csdn.net/develop/Read_Article.asp?Id=19171 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 http://www.csdn.net/develop/Read_Article.asp?Id=19171 public class TestGetPart{ public TestGetPart() { } public static void println(String message) { System.out.println(message); } private static org.w3c.dom.Document getParsedXmlDoc(java.io.InputStream XmlInput) { org.w3c.dom.Document indoc = null; javax.xml.parsers.DocumentBuilderFactory factory; javax.xml.parsers.DocumentBuilder builder; try { factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setValidating(false); builder = factory.newDocumentBuilder(); indoc = builder.parse(XmlInput); indoc.normalize(); } catch (Exception e) { println("解析文件错,XML文件格式不对。堆栈信息如下"); } return indoc; } public static int spaceStep, spaceCount; public static void printDomTree(org.w3c.dom.Node node) { spaceStep = 4; spaceCount = 0; try { saveDoc(node); } catch (Exception e) { println(e.toString()); } } private static String addSpace(String line, int totalSpace) { String sp = ""; for (int i = 0; i < (totalSpace - line.length()) / 2; i++) { sp += "-"; } if (line.length() % 2 != 0) { line += "-"; } return sp + line + sp; } protected static String getSpace() { String str = ""; for (int i = 0; i < spaceCount; i++) { str = str + " "; } return str; } public static void print(String message) { System.out.print(message); } private static void print(String str, boolean space) throws java.io. IOException { if (space) { str = getSpace() + str; } print(str); } private static void println(String str, boolean space) throws java.io. IOException { if (space) { str = getSpace() + str; } str += "\r\n"; print(str); } private static void saveDoc(org.w3c.dom.Node node) throws java.io. IOException { if (node == null) { print("", false); } else if (node.getNodeName().indexOf("#") >= 0) { String name = node.getNodeName().trim(); String value = node.getNodeValue().trim(); if (name.equals("#text") && value.equals("")) { return; } println(value, true);// println( "[name]:\""+node.getNodeName().trim()+"\"[value]:\""+node.getNodeValue().trim()+"\"" ,true ); return; } else if (node.getFirstChild() == null) { print("<" + node.getNodeName(), true); for (int i = 0; i < (node.getAttributes()).getLength(); i++) { org.w3c.dom.Node attrNode = node.getAttributes().item(i); print(" " + attrNode.getNodeName() + "=\"" + attrNode.getNodeValue() + "\"", false); } println("/>", false); } else { print("<" + node.getNodeName(), true); for (int i = 0; i < (node.getAttributes()).getLength(); i++) { org.w3c.dom.Node attrNode = node.getAttributes().item(i); print(" " + attrNode.getNodeName() + "=\"" + attrNode.getNodeValue() + "\"", false); } println(">", false); spaceCount += spaceStep; for (int i = 0; i < node.getChildNodes().getLength(); i++) { saveDoc(node.getChildNodes().item(i)); } spaceCount -= spaceStep; println("</" + node.getNodeName() + ">", true); } } public static void printTextAsXml(String text) { try { java.io.ByteArrayInputStream sbi = new java.io.ByteArrayInputStream( text.getBytes()); org.w3c.dom.Document indoc = getParsedXmlDoc(sbi); if (indoc != null) { printDomTree(indoc.getLastChild()); } } catch (Throwable t) { println(t.toString()); println("Error happened while parsing xml,Original text is:\r\n" + text); } } public static void main(String[] args) { String text = "<speech>" + "<speaker>catesby</speaker>" + "<line>The princes both make high account of you;</line>" + "<stagedir>aside</stagedir>" + "<line>For they account his head upon the bridge.</line>" + "</speech>"; printTextAsXml(text); }} JDOM在更新xml方面比较方便,其他的,与JDK1.4方面相比,优势不是很明显。 利用DOM读取XML文件的程序:import javax.xml.parsers.*;import org.w3c.dom.*;import java.io.*;/** *使用DOM提取XML内容的例子 */class BookParser{ public static void main(String[] args){ try{ //获取一个XML解析器 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); //解析XML文件 Document document=builder.parse(new File("books.xml")); //去掉XML文档中空白部分 document.normalize(); //获取根节点并打印根节点的名称 Element root=document.getDocumentElement(); System.out.println("根原始的名称:"+root.getTagName()); //获取所有的"book"标记,它是一个NodeList对象 NodeList books=root.getElementsByTagName("book"); //遍历NodeList System.out.println("书本列表"); for(int i=0;i<books.getLength();i++){ //获取books中的每一个元素 Element book=(Element)books.item(i); //获取每个"book"标记的"id"属性 String book_id=book.getAttribute("id");//或book.getAttributeNode("id").getValue(); System.out.println("序号:"+book_id); //获取"book"标记下的每个元素 System.out.print("作者:"); System.out.println(book.getElementsByTagName("author").item(0).getFirstChild().getNodeValue()); System.out.print("标题:"); System.out.println(book.getElementsByTagName("title").item(0).getFirstChild().getNodeValue()); //获取"publish_date"元素 Element publishDate=(Element)book.getElementsByTagName("publish_date").item(0); //获取"publish_date"元素下的每个子元素 String year=publishDate.getElementsByTagName("year").item(0).getFirstChild().getNodeValue(); String month=publishDate.getElementsByTagName("month").item(0).getFirstChild().getNodeValue(); String day=publishDate.getElementsByTagName("day").item(0).getFirstChild().getNodeValue(); System.out.println("出版日期:"+year+"年"+month+"月"+day+"日"); System.out.print("描述:"); System.out.println(book.getElementsByTagName("description").item(0).getFirstChild().getNodeValue()); System.out.println("--------------------"); } } catch(Exception e2){} }}相应的XML文件:<?xml version="1.0" encoding="UTF-8"?><catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <publish_date> <year>2000</year> <month>10</month> <day>1</day> </publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <publish_date> <year>2000</year> <month>12</month> <day>16</day> </publish_date> <description>A former architect battles corporate zombies.</description> </book> <book id="bk103"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <publish_date> <year>2000</year> <month>11</month> <day>17</day> </publish_date> <description>After the collapse of a nanotechnology society in England.</description> </book> <book id="bk104"> <author>leony</author> <title>Maeve Ascendant</title> <publish_date> <year>2000</year> <month>11</month> <day>17</day> </publish_date> <description>XML</description> </book></catalog>把两个文件copy在同一目录下,编译运行即可 java如何实现远程上传功能 提交多个实体Bean对象的数据该怎么办?或者提交多个form表单 关于存储过程的问题 关于反射 帮帮忙 谢谢! 求救!!证书验证的问题!! 实时发送email 你是怎样积累项目开发经验的?说者有分哦! MyEclipse无辜退出 linux下怎么配置jdbc 访问oracle ,知情者请告知 json数据从action中传到前台页面的问题 NoClassDefFoundError: oracle/sql/ClobDBAccess!!困绕好多日子了,向zez前辈及各位熟悉weblogic+oracle应用的大侠求救!!!一定送分 高分求搜索引擎的网路搜索算法
public class TestGetPart
{
public TestGetPart()
{
} public static void println(String message)
{
System.out.println(message);
} private static org.w3c.dom.Document getParsedXmlDoc(java.io.InputStream
XmlInput)
{
org.w3c.dom.Document indoc = null;
javax.xml.parsers.DocumentBuilderFactory factory;
javax.xml.parsers.DocumentBuilder builder;
try
{
factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setValidating(false);
builder = factory.newDocumentBuilder();
indoc = builder.parse(XmlInput);
indoc.normalize();
}
catch (Exception e)
{
println("解析文件错,XML文件格式不对。堆栈信息如下");
}
return indoc;
} public static int spaceStep, spaceCount;
public static void printDomTree(org.w3c.dom.Node node)
{
spaceStep = 4;
spaceCount = 0;
try
{
saveDoc(node);
}
catch (Exception e)
{
println(e.toString());
}
} private static String addSpace(String line, int totalSpace)
{
String sp = "";
for (int i = 0; i < (totalSpace - line.length()) / 2; i++)
{
sp += "-";
}
if (line.length() % 2 != 0)
{
line += "-";
}
return sp + line + sp;
} protected static String getSpace()
{
String str = "";
for (int i = 0; i < spaceCount; i++)
{
str = str + " ";
}
return str;
} public static void print(String message)
{
System.out.print(message);
} private static void print(String str, boolean space) throws java.io.
IOException
{
if (space)
{
str = getSpace() + str;
}
print(str);
} private static void println(String str, boolean space) throws java.io.
IOException
{
if (space)
{
str = getSpace() + str;
}
str += "\r\n";
print(str);
} private static void saveDoc(org.w3c.dom.Node node) throws java.io.
IOException
{
if (node == null)
{
print("", false);
}
else if (node.getNodeName().indexOf("#") >= 0)
{
String name = node.getNodeName().trim();
String value = node.getNodeValue().trim();
if (name.equals("#text") && value.equals(""))
{
return;
}
println(value, true);
// println( "[name]:\""+node.getNodeName().trim()+"\"[value]:\""+node.getNodeValue().trim()+"\"" ,true );
return;
}
else if (node.getFirstChild() == null)
{
print("<" + node.getNodeName(), true);
for (int i = 0; i < (node.getAttributes()).getLength(); i++)
{
org.w3c.dom.Node attrNode = node.getAttributes().item(i);
print(" " + attrNode.getNodeName() + "=\"" +
attrNode.getNodeValue() + "\"", false);
}
println("/>", false);
}
else
{
print("<" + node.getNodeName(), true);
for (int i = 0; i < (node.getAttributes()).getLength(); i++)
{
org.w3c.dom.Node attrNode = node.getAttributes().item(i);
print(" " + attrNode.getNodeName() + "=\"" +
attrNode.getNodeValue() + "\"", false);
}
println(">", false);
spaceCount += spaceStep;
for (int i = 0; i < node.getChildNodes().getLength(); i++)
{
saveDoc(node.getChildNodes().item(i));
}
spaceCount -= spaceStep;
println("</" + node.getNodeName() + ">", true);
}
} public static void printTextAsXml(String text)
{
try
{
java.io.ByteArrayInputStream sbi = new java.io.ByteArrayInputStream(
text.getBytes());
org.w3c.dom.Document indoc = getParsedXmlDoc(sbi);
if (indoc != null)
{
printDomTree(indoc.getLastChild());
}
}
catch (Throwable t)
{
println(t.toString());
println("Error happened while parsing xml,Original text is:\r\n" +
text); }
} public static void main(String[] args)
{
String text = "<speech>"
+ "<speaker>catesby</speaker>"
+ "<line>The princes both make high account of you;</line>"
+ "<stagedir>aside</stagedir>"
+ "<line>For they account his head upon the bridge.</line>"
+ "</speech>";
printTextAsXml(text);
}
}
其他的,与JDK1.4方面相比,优势不是很明显。
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;/**
*使用DOM提取XML内容的例子
*/
class BookParser{
public static void main(String[] args){
try{
//获取一个XML解析器
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
//解析XML文件
Document document=builder.parse(new File("books.xml"));
//去掉XML文档中空白部分
document.normalize();
//获取根节点并打印根节点的名称
Element root=document.getDocumentElement();
System.out.println("根原始的名称:"+root.getTagName());
//获取所有的"book"标记,它是一个NodeList对象
NodeList books=root.getElementsByTagName("book");
//遍历NodeList
System.out.println("书本列表");
for(int i=0;i<books.getLength();i++){
//获取books中的每一个元素
Element book=(Element)books.item(i);
//获取每个"book"标记的"id"属性
String book_id=book.getAttribute("id");//或book.getAttributeNode("id").getValue();
System.out.println("序号:"+book_id);
//获取"book"标记下的每个元素
System.out.print("作者:");
System.out.println(book.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
System.out.print("标题:");
System.out.println(book.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());
//获取"publish_date"元素
Element publishDate=(Element)book.getElementsByTagName("publish_date").item(0);
//获取"publish_date"元素下的每个子元素
String year=publishDate.getElementsByTagName("year").item(0).getFirstChild().getNodeValue();
String month=publishDate.getElementsByTagName("month").item(0).getFirstChild().getNodeValue();
String day=publishDate.getElementsByTagName("day").item(0).getFirstChild().getNodeValue();
System.out.println("出版日期:"+year+"年"+month+"月"+day+"日");
System.out.print("描述:");
System.out.println(book.getElementsByTagName("description").item(0).getFirstChild().getNodeValue());
System.out.println("--------------------");
}
}
catch(Exception e2){}
}
}相应的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<publish_date>
<year>2000</year>
<month>10</month>
<day>1</day>
</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<publish_date>
<year>2000</year>
<month>12</month>
<day>16</day>
</publish_date>
<description>A former architect battles corporate zombies.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<publish_date>
<year>2000</year>
<month>11</month>
<day>17</day>
</publish_date>
<description>After the collapse of a nanotechnology society in England.</description>
</book>
<book id="bk104">
<author>leony</author>
<title>Maeve Ascendant</title>
<publish_date>
<year>2000</year>
<month>11</month>
<day>17</day>
</publish_date>
<description>XML</description>
</book>
</catalog>
把两个文件copy在同一目录下,编译运行即可