使用 Java 中的 SAX 解析器从 XML 获取所有标记和值 [英] Get all the tags and values from XML using SAX parser in java
问题描述
我正在尝试使用 SAX 解析 xml.我希望以嵌套方式从 xml 中获取所有标签及其值.是否可以使用 SAX 解析器.谁能给我举个例子.(我认为 SAX 比 w3 文档生成器更高效,所以我选择了它.我想知道天气我在正确的道路上)我正在附上我的 Java 程序
I am trying to parse xml using SAX. I want all the tags and their values from xml in nested way. Is it possible with SAX parser. Can anyone provide me an example. (I think SAX is efficient than w3 document builder, So I chose it. And I want to know weather I'm on the right path) I'm attaching my java program
class MySAXApp extends DefaultHandler
{
public MySAXApp ()
{
super();
}
public void startDocument ()
{
System.out.println("Start document");
}
public void endDocument ()
{
System.out.println("End document");
}
public void startElement (String uri, String name,
String qName, Attributes atts)
{
System.out.println(atts.getLength());
if ("".equals (uri))
System.out.println("Start element: " + qName);
else
System.out.println("Start element: {" + uri + "}" + name);
}
}
这是我的 XML.这是一个有效的 xml 吗?像这样写xml有没有错误
Here is my XML. Is this a valid xml? Are there any errors in writing xml like this
<?xml version="1.0" encoding="utf-8"?>
<CustomerReport xsi:schemaLocation="Customer.xsd">
<Customer>
<CustomerName>str1234</CustomerName>
<CustomerStatus>str1234</CustomerStatus>
<PurchaceOrders>
<PurchaceOrder>
<PurchaceOrderName>str1234</PurchaceOrderName>
</PurchaceOrder>
</PurchaceOrders>
</Customer>
</CustomerReport>
我是 XML 的新手.有人可以帮我吗
I'm new to XML. Can someone help me on this
推荐答案
当您说 SAX更高效"时,您的实际意思是 SAX 解析器完成最少的工作,将大部分工作留给应用.这意味着您(应用程序编写者)有更多的代码要编写,而且正如您发现的那样,这是非常棘手的代码.因为编写 XML 解析器的人是比您更有经验的 Java 编码员,所以很可能您在代码中做的工作越多,在解析器中做的工作越少,整个应用程序的效率就越低.因此,鉴于您的经验水平,我的建议是使用解析方法,让库尽可能多地完成工作.我建议使用 JDOM2.
When you say SAX is "more efficient", what you actually mean is that a SAX parser does the minimum amount of work, leaving most of the work to the application. That means you (the application writer) have more code to write, and it's quite tricky code as you are discovering. Because the people who write XML parsers are much more experienced Java coders than you are, it's likely that the more work you do in your code, and the less you do within the parser, the less efficient your overall application will be. So given your level of experience, my advice would be to use a parsing approach where the library does as much as possible of the work. I would suggest using JDOM2.
这篇关于使用 Java 中的 SAX 解析器从 XML 获取所有标记和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!