Java 需要如何正确解析的帮助吗
我是一个学习如何进行XML解析的新手,并收到了一份使用Java解析XML文件的家庭作业 这是XML文件:Java 需要如何正确解析的帮助吗,java,xml,xml-parsing,Java,Xml,Xml Parsing,我是一个学习如何进行XML解析的新手,并收到了一份使用Java解析XML文件的家庭作业 这是XML文件: <?xml version="1.0" ?> <deliveries> <van id="VID-12345"> <package> <product taxable="true" productName="Headphones" isbn="123456" unitPrice="10.00
<?xml version="1.0" ?>
<deliveries>
<van id="VID-12345">
<package>
<product taxable="true" productName="Headphones" isbn="123456" unitPrice="10.00" quantity="1"/>
<product taxable="false" productName="Milk" isbn="234567" unitPrice="2.00" quantity="2"/>
<customer lastName="Adams" firstName="Maurice" streetAddress="123 4th St" zipCode="13126" accountNumber="ACCT-54321"/>
</package>
<package>
<product taxable="true" productName="Snickers" isbn="345678" unitPrice="1.00" quantity="1"/>
<product taxable="false" productName="Milk" isbn="234567" unitPrice="2.00" quantity="1"/>
<customer lastName="Baxter" firstName="Robert" streetAddress="234 5th St" zipCode="13126" accountNumber="ACCT-65432"/>
</package>
</van>
<cart id="VID-23456">
<package>
<product taxable="true" productName="Snickers" isbn="345678" unitPrice="1.00" quantity="1"/>
<customer lastName="Charles" firstName="Steven" streetAddress="345 6th St" zipCode="13126" accountNumber="ACCT-76543"/>
</package>
</cart>
</deliveries>
如何将其解析为建议的格式?我已经阅读了很多教程和例子,但我找不到一个可以帮助我。根据我所读到的内容,我最好的猜测是它与制作列表或创建要解析的对象有关。我也不知道如何计算“总计”(即每个“包装”中所有项目的单价*数量之和)。一个解决方案会很好,但一个详细的提示(或相关的教程链接)也会有助于指导我。我将非常感谢任何帮助。这是我目前正在编写的代码:
public class MyHandler extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
System.out.println("---=== Report ===---");
}
@Override
public void endDocument() throws SAXException {
System.out.println("---=== End of Report ===---");
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("van")) {
System.out.println("Van (" + attributes.getValue("id") + ")");
}
if (qName.equalsIgnoreCase("customer")) {
System.out.println(" Customer");
System.out.println(" " + attributes.getValue("lastName") + ", " + attributes.getValue("firstName") + " at " + attributes.getValue("streetAddress") + ", " + attributes.getValue("zipCode"));
}
if (qName.equalsIgnoreCase("cart")) {
System.out.println("Cart (" + attributes.getValue("id") + ")");
}
if (qName.equalsIgnoreCase("product")) {
double sum = Double.parseDouble(attributes.getValue("unitPrice")) * Integer.parseInt(attributes.getValue("quantity"));
System.out.println(sum);
}
}
}
结果(不正确):
编辑:我找到了一种打印出我想要的确切格式的方法,但我仍然不认为这是最好的方法,我想知道一种更好的方法
public class MyHandler extends DefaultHandler {
private boolean bCustomer = false;
private double total = 0;
private DecimalFormat df = new DecimalFormat("#.00");
@Override
public void startDocument() throws SAXException {
System.out.println("---=== Report ===---");
}
@Override
public void endDocument() throws SAXException {
printTotal();
System.out.println("---=== End of Report ===---");
}
private void printTotal() {
System.out.println(" Total");
System.out.println(" $" + df.format(total));
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("cart")) {
if (total != 0) {
printTotal();
total = 0;
}
System.out.println("Cart (" + attributes.getValue("id") + ")");
System.out.println(" Customer");
} else if (qName.equalsIgnoreCase("drone")) {
if (total != 0) {
printTotal();
total = 0;
}
System.out.println("Drone (" + attributes.getValue("id") + ")");
System.out.println(" Customer");
} else if (qName.equalsIgnoreCase("scooter")) {
if (total != 0) {
printTotal();
total = 0;
}
System.out.println("Scooter (" + attributes.getValue("id") + ")");
System.out.println(" Customer");
} else if (qName.equalsIgnoreCase("van")) {
if (total != 0) {
printTotal();
total = 0;
}
System.out.println("Van (" + attributes.getValue("id") + ")");
System.out.println(" Customer");
}
if (qName.equalsIgnoreCase("product")) {
boolean bTax = Boolean.parseBoolean(attributes.getValue("taxable"));
double unitPrice = Double.parseDouble(attributes.getValue("unitPrice"));
int quantity = Integer.parseInt(attributes.getValue("quantity"));
if (bTax) {
Taxable taxable = new Taxable(attributes.getValue("productName"), attributes.getValue("isbn"), unitPrice, quantity);
total = total + taxable.getPrice();
} else {
NonTaxable nonTaxable = new NonTaxable(attributes.getValue("productName"), attributes.getValue("isbn"), unitPrice, quantity);
total = total + nonTaxable.getPrice();
}
}
if (qName.equalsIgnoreCase("customer")) {
if (!bCustomer) {
bCustomer = true;
}
System.out.println(" " + attributes.getValue("lastName") + ", " + attributes.getValue("firstName") + " at " + attributes.getValue("streetAddress") + ", " + attributes.getValue("zipCode"));
}
}
}
是指向我的完整源代码的链接,其中还包含我决定不添加的XML文件所需的对象,因为这会使我的文章太长,阅读起来很痛苦。谢谢你的帮助 import org.dom4j.DocumentException;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.List;
/**
* @Author: panlf
* @Date: 2019/9/16 9:27
*/
public class Dom4jTeset {
public static void main(String[] args) throws DocumentException {
Element root = DocumentHelper.parseText(XML).getRootElement();
List<Element> all = root.elements();
for (Element child : all) {
System.out.println(child.getQName().getName()+" ("+ child.attribute("id").getValue()+")");
System.out.println(" Customer");
double sum=0;
for (Element pack : child.elements()) {
Element customer = pack.elements("customer").get(0);
for (Element prod : pack.elements()) {
if(prod.getQName().getName().equals("customer"))continue;
String unitPrice = prod.attribute("unitPrice").getValue();
sum+=Double.parseDouble(prod.attribute("unitPrice").getValue())* Integer.parseInt(prod.attribute("quantity").getValue());
}
System.out.println(" "+ customer.attribute("lastName").getValue()+", "+ customer.attribute("firstName").getValue()+ " at " + customer.attribute("streetAddress").getValue()+" "+ customer.attribute("zipCode").getValue());
}
System.out.println(" Total");
System.out.println(" $"+sum);
}
}
private static String XML="<?xml version=\"1.0\" ?>\n" +
"<deliveries>\n" +
" <van id=\"VID-12345\">\n" +
" <package>\n" +
" <product taxable=\"true\" productName=\"Headphones\" isbn=\"123456\" unitPrice=\"10.00\" quantity=\"1\"/>\n" +
" <product taxable=\"false\" productName=\"Milk\" isbn=\"234567\" unitPrice=\"2.00\" quantity=\"2\"/>\n" +
" <customer lastName=\"Adams\" firstName=\"Maurice\" streetAddress=\"123 4th St\" zipCode=\"13126\" accountNumber=\"ACCT-54321\"/>\n" +
" </package>\n" +
" <package>\n" +
" <product taxable=\"true\" productName=\"Snickers\" isbn=\"345678\" unitPrice=\"1.00\" quantity=\"1\"/>\n" +
" <product taxable=\"false\" productName=\"Milk\" isbn=\"234567\" unitPrice=\"2.00\" quantity=\"1\"/>\n" +
" <customer lastName=\"Baxter\" firstName=\"Robert\" streetAddress=\"234 5th St\" zipCode=\"13126\" accountNumber=\"ACCT-65432\"/>\n" +
" </package>\n" +
" </van>\n" +
" <cart id=\"VID-23456\">\n" +
" <package>\n" +
" <product taxable=\"true\" productName=\"Snickers\" isbn=\"345678\" unitPrice=\"1.00\" quantity=\"1\"/>\n" +
" <customer lastName=\"Charles\" firstName=\"Steven\" streetAddress=\"345 6th St\" zipCode=\"13126\" accountNumber=\"ACCT-76543\"/>\n" +
" </package>\n" +
" </cart>\n" +
"</deliveries>";
}
导入org.dom4j.DocumentHelper;
导入org.dom4j.Element;
导入java.util.List;
/**
*@Author:panlf
*@日期:2019/9/16 9:27
*/
公共类Dom4jTeset{
公共静态void main(字符串[]args)引发DocumentException{
Element root=DocumentHelper.parseText(XML).getRootElement();
List all=root.elements();
for(元素子元素:全部){
System.out.println(child.getQName().getName()+”(“+child.attribute(“id”).getValue()+”));
系统输出打印项次(“客户”);
双和=0;
对于(元素包:child.elements()){
元素客户=包装元素(“客户”).get(0);
对于(元素产品:pack.elements()){
如果(prod.getQName().getName().equals(“客户”))继续;
字符串unitPrice=prod.attribute(“unitPrice”).getValue();
sum+=Double.parseDouble(prod.attribute(“单价”).getValue())*Integer.parseInt(prod.attribute(“数量”).getValue());
}
System.out.println(“+customer.attribute(“lastName”).getValue()+”,“+customer.attribute(“firstName”).getValue()+”位于“+customer.attribute(“streetAddress”).getValue()+”+customer.attribute(“zipCode”).getValue()”;
}
系统输出打印项次(“总计”);
系统输出打印项次(“$”+总和);
}
}
私有静态字符串XML=“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
"";
}
看起来您很快就能获得所需的输出。我认为最好使用所需变量(firstname、lastname、address等)为每个对象(Van、Customer、Cart等)创建单独的类,并在解析和初始化所需对象(交付将包含List和List)后,创建一个以所需格式输出报告的方法。(不是最简单的/最小的方法,但肯定是在OOP原则中)我已经有了你说的所有类,但是因为这会让我的文章变得很长,所以我决定不包括它们(但如果你觉得有必要,我可以)。您能否进一步解释一下如何初始化要解析的对象并生成以特定格式输出报告的方法?谢谢。我可能说的是胡言乱语,因为现在是早上6点,我没有睡觉,但是因为你有类和startElement
方法,看起来它能够获得特定的值,然后不要将它们打印到Sys.out,试着初始化对象。在调用输出报告的方法之后。需要初始化的对象可能是实例或类变量。在startElement
中初始化对象可能需要一件事,那就是能够区分它当前是否正在读取van或cart的包。Sry如果这没有帮助,会在睡觉后尝试。是的,我认为这是胡说八道,cya在几个小时内。你正在让你的生活变得比试图同时解析和生成输出更复杂。相反,将XML解析为Java对象结构(包含包列表、产品列表和客户列表的货车和推车)。这可以通过像JAXB这样的XML到对象映射库来实现。然后对这些对象执行任何需要执行的操作(通过循环这些对象中包含的列表并计算所需的总和),这是使用dom4jjarcare来详细说明的吗?谢谢
public class MyHandler extends DefaultHandler {
private boolean bCustomer = false;
private double total = 0;
private DecimalFormat df = new DecimalFormat("#.00");
@Override
public void startDocument() throws SAXException {
System.out.println("---=== Report ===---");
}
@Override
public void endDocument() throws SAXException {
printTotal();
System.out.println("---=== End of Report ===---");
}
private void printTotal() {
System.out.println(" Total");
System.out.println(" $" + df.format(total));
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("cart")) {
if (total != 0) {
printTotal();
total = 0;
}
System.out.println("Cart (" + attributes.getValue("id") + ")");
System.out.println(" Customer");
} else if (qName.equalsIgnoreCase("drone")) {
if (total != 0) {
printTotal();
total = 0;
}
System.out.println("Drone (" + attributes.getValue("id") + ")");
System.out.println(" Customer");
} else if (qName.equalsIgnoreCase("scooter")) {
if (total != 0) {
printTotal();
total = 0;
}
System.out.println("Scooter (" + attributes.getValue("id") + ")");
System.out.println(" Customer");
} else if (qName.equalsIgnoreCase("van")) {
if (total != 0) {
printTotal();
total = 0;
}
System.out.println("Van (" + attributes.getValue("id") + ")");
System.out.println(" Customer");
}
if (qName.equalsIgnoreCase("product")) {
boolean bTax = Boolean.parseBoolean(attributes.getValue("taxable"));
double unitPrice = Double.parseDouble(attributes.getValue("unitPrice"));
int quantity = Integer.parseInt(attributes.getValue("quantity"));
if (bTax) {
Taxable taxable = new Taxable(attributes.getValue("productName"), attributes.getValue("isbn"), unitPrice, quantity);
total = total + taxable.getPrice();
} else {
NonTaxable nonTaxable = new NonTaxable(attributes.getValue("productName"), attributes.getValue("isbn"), unitPrice, quantity);
total = total + nonTaxable.getPrice();
}
}
if (qName.equalsIgnoreCase("customer")) {
if (!bCustomer) {
bCustomer = true;
}
System.out.println(" " + attributes.getValue("lastName") + ", " + attributes.getValue("firstName") + " at " + attributes.getValue("streetAddress") + ", " + attributes.getValue("zipCode"));
}
}
}
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.List;
/**
* @Author: panlf
* @Date: 2019/9/16 9:27
*/
public class Dom4jTeset {
public static void main(String[] args) throws DocumentException {
Element root = DocumentHelper.parseText(XML).getRootElement();
List<Element> all = root.elements();
for (Element child : all) {
System.out.println(child.getQName().getName()+" ("+ child.attribute("id").getValue()+")");
System.out.println(" Customer");
double sum=0;
for (Element pack : child.elements()) {
Element customer = pack.elements("customer").get(0);
for (Element prod : pack.elements()) {
if(prod.getQName().getName().equals("customer"))continue;
String unitPrice = prod.attribute("unitPrice").getValue();
sum+=Double.parseDouble(prod.attribute("unitPrice").getValue())* Integer.parseInt(prod.attribute("quantity").getValue());
}
System.out.println(" "+ customer.attribute("lastName").getValue()+", "+ customer.attribute("firstName").getValue()+ " at " + customer.attribute("streetAddress").getValue()+" "+ customer.attribute("zipCode").getValue());
}
System.out.println(" Total");
System.out.println(" $"+sum);
}
}
private static String XML="<?xml version=\"1.0\" ?>\n" +
"<deliveries>\n" +
" <van id=\"VID-12345\">\n" +
" <package>\n" +
" <product taxable=\"true\" productName=\"Headphones\" isbn=\"123456\" unitPrice=\"10.00\" quantity=\"1\"/>\n" +
" <product taxable=\"false\" productName=\"Milk\" isbn=\"234567\" unitPrice=\"2.00\" quantity=\"2\"/>\n" +
" <customer lastName=\"Adams\" firstName=\"Maurice\" streetAddress=\"123 4th St\" zipCode=\"13126\" accountNumber=\"ACCT-54321\"/>\n" +
" </package>\n" +
" <package>\n" +
" <product taxable=\"true\" productName=\"Snickers\" isbn=\"345678\" unitPrice=\"1.00\" quantity=\"1\"/>\n" +
" <product taxable=\"false\" productName=\"Milk\" isbn=\"234567\" unitPrice=\"2.00\" quantity=\"1\"/>\n" +
" <customer lastName=\"Baxter\" firstName=\"Robert\" streetAddress=\"234 5th St\" zipCode=\"13126\" accountNumber=\"ACCT-65432\"/>\n" +
" </package>\n" +
" </van>\n" +
" <cart id=\"VID-23456\">\n" +
" <package>\n" +
" <product taxable=\"true\" productName=\"Snickers\" isbn=\"345678\" unitPrice=\"1.00\" quantity=\"1\"/>\n" +
" <customer lastName=\"Charles\" firstName=\"Steven\" streetAddress=\"345 6th St\" zipCode=\"13126\" accountNumber=\"ACCT-76543\"/>\n" +
" </package>\n" +
" </cart>\n" +
"</deliveries>";
}