会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
爱睇资讯
IT资讯,最新最前沿。我们的口号:能解决实际问题的软件才是好软件!
业界新闻均来自
華爾街日報 中文網
博客园
首页
新随笔
联系
订阅
管理
JAXP-DOM解释XML最清晰的程序代码
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
//
JAXP
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
//
DOM
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public
class
TestDOMParsing
{
public
static
void
main(String[] args)
{
try
{
if
(args.length
!=
1
)
{
System.err.println (
"
Usage: java TestDOMParsing [filename]
"
);
System.exit (
1
);
}
//
Get Document Builder Factory
DocumentBuilderFactory factory
=
DocumentBuilderFactory.newInstance();
//
Leave off validation, and turn off namespaces
factory.setValidating(
false
);
factory.setNamespaceAware(
false
);
DocumentBuilder builder
=
factory.newDocumentBuilder();
Document doc
=
builder.parse(
new
File(args[
0
]));
//
Print the document from the DOM tree and
//
feed it an initial indentation of nothing
printNode(doc,
""
);
}
catch
(ParserConfigurationException e)
{
System.
out
.println(
"
The underlying parser does not support the requested features.
"
);
}
catch
(FactoryConfigurationError e)
{
System.
out
.println(
"
Error occurred obtaining Document Builder Factory.
"
);
}
catch
(Exception e)
{
e.printStackTrace();
}
}
private
static
void
printNode(Node node, String indent)
{
switch
(node.getNodeType())
{
case
Node.DOCUMENT_NODE:
System.
out
.println(
"
<xml version=\
"
1.0
\
"
>\n
"
);
//
recurse on each child
NodeList nodes
=
node.getChildNodes();
if
(nodes
!=
null
)
{
for
(
int
i
=
0
; i
<
nodes.getLength(); i
++
)
{
printNode(nodes.item(i),
""
);
}
}
break
;
case
Node.ELEMENT_NODE:
String name
=
node.getNodeName();
System.
out
.print(indent
+
"
<
"
+
name);
NamedNodeMap attributes
=
node.getAttributes();
for
(
int
i
=
0
; i
<
attributes.getLength(); i
++
)
{
Node current
=
attributes.item(i);
System.
out
.print(
"
"
+
current.getNodeName()
+
"
=\
""
+ current.getNodeValue() +
"
\
""
);
}
System.
out
.print(
"
>
"
);
//
recurse on each child
NodeList children
=
node.getChildNodes();
if
(children
!=
null
)
{
for
(
int
i
=
0
; i
<
children.getLength(); i
++
)
{
printNode(children.item(i), indent
+
"
"
);
}
}
System.
out
.print(
"
</
"
+
name
+
"
>
"
);
break
;
case
Node.TEXT_NODE:
System.
out
.print(node.getNodeValue());
break
;
}
}
}
posted @
2005-06-08 10:54
Rookie.Zhang
阅读(
653
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告