domparser java_java – DOM XML Parser示例

xml无效. (您可以在线验证您的xml:

http://www.w3schools.com/xml/xml_validator.asp)

您可以尝试使用此xml

1

1.0

Hack off tiles and make good walls

100

50

20

5000

1

1.03

Test

45

100

4500

0

并保留你的代码

package test;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import java.io.File;

import java.io.IOException;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

public class TestXml{

public static void main (String[] args) throws ParserConfigurationException{

TestXml t = new TestXml();

t.readXml() ;

}

public void readXml () throws ParserConfigurationException{

File fXmlFile = new File("D:/formdata.xml");

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

Document doc = null;

try {

doc = dBuilder.parse(fXmlFile);

} catch (SAXException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("record");

System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("\nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("Item No : " + eElement.getElementsByTagName("item_no").item(0).getTextContent());

System.out.println("Description : " + eElement.getElementsByTagName("description").item(0).getTextContent());

System.out.println("price : " + eElement.getElementsByTagName("price").item(0).getTextContent());

System.out.println("base qty : " + eElement.getElementsByTagName("base_qty").item(0).getTextContent());

System.out.println("Var qty : " + eElement.getElementsByTagName("var_qty").item(0).getTextContent());

System.out.println("Base price : " + eElement.getElementsByTagName("base_price_").item(0).getTextContent());

}}}}

你会得到这个结果

Root element :records

----------------------------

Current Element :record

Item No : 1.0

Description : Hack off tiles and make good walls

price : 100

base qty : 50

Var qty : 20

Base price : 5000

Current Element :record

Item No : 1.03

Description : Test

price : 45

base qty : 100

Var qty : 4500

Base price : 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值