java如何读取xml节点元素值?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java如何读取xml节点元素值?相关的知识,希望对你有一定的参考价值。
java读取xml节点元素,主要使用java提供的解析xml的工具类SAXParserFactory,如下代码:
package xml.xmlreader;import java.io.File;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class CFGParser //解析xml文件的工具类
private Properties props;
public Properties getProps()
return props;
public void setProps(Properties props)
this.props = props;
public void parse(String filename) throws Exception
CFGHandler handler = new CFGHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
URL confURL = super.getClass().getClassLoader().getResource(filename);
if (confURL == null)
System.out.println("Can\'t find configration file.");
return;
try
parser.parse(confURL.toString(), handler);
this.props = handler.getProps();
finally
factory = null;
parser = null;
handler = null;
public void parseFile(String filename)
throws Exception
CFGHandler handler = new CFGHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
File f = new File(filename);
if ((f == null) || (!f.exists()))
return;
try
parser.parse(f, handler);
this.props = handler.getProps();
finally
factory = null;
parser = null;
handler = null;
package xml.xmlreader;
import java.util.Properties;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class CFGHandler extends DefaultHandler
private Properties props;
private String currentSet;
private String currentName;
private StringBuffer currentValue = new StringBuffer();
public CFGHandler()
this.props = new Properties();
public Properties getProps()
return this.props;
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException
this.currentValue.delete(0, this.currentValue.length());
this.currentName = qName;
public void characters(char[] ch, int start, int length) throws SAXException
this.currentValue.append(ch, start, length);
public void endElement(String uri, String localName, String qName)
throws SAXException
this.props.put(qName.toLowerCase(), this.currentValue.toString().trim());
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<xml-body>
<refresh_userlist desc="用户列表刷新间隔时间(秒)">6</refresh_userlist>
<refresh_message desc="短消息刷新间隔时间(秒)">10</refresh_message>
<morningbegin desc="上午上班时间">23:00</morningbegin>
<morningend desc="上午下班时间">12:00</morningend>
<afternoonbegin desc="下午上班时间">18:00</afternoonbegin>
</xml-body>
jsp获取各个节点的值:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<jsp:useBean id="cfgp" scope="page" class="xml.xmlreader.CFGParser"></jsp:useBean>
<body>
<%
cfgp.parse("kaoqin.xml");
Properties pro = cfgp.getProps();
String stTime = pro.getProperty("morningbegin");
String edTime = pro.getProperty("morningend");
String afternoonbegin = pro.getProperty("afternoonbegin");
out.println(stTime+"\\n"+edTime+"\\n"+afternoonbegin);
System.out.println(stTime+"\\n"+edTime+"\\n"+afternoonbegin);
%>
</body>
</html> 参考技术A element.getAttributeValue("id")本回答被提问者采纳
如何从 xml 文件中读取单个节点值
【中文标题】如何从 xml 文件中读取单个节点值【英文标题】:How to read single node value from xml file 【发布时间】:2013-08-17 12:33:50 【问题描述】:您好,我正在尝试从 xml 中获取值,但它显示节点为空。
这是我的 xml 文件。
<?xml version="1.0" encoding="utf-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.cfhdocmail.com/TestAPI2/Result.xsd https://www.cfhdocmail.com/TestAPI2/Result.xsd" xmlns="https://www.cfhdocmail.com/TestAPI2/Result.xsd">
<data>
<key>MailingGUID</key>
<value>0aa2b2e3-7afa-4002-ab2f-9eb4cbe33ae7</value>
</data>
<data>
<key>OrderRef</key>
<value>52186</value>
</data>
</result>
我想获得 "MailingGUID" 值。
这是我尝试过的代码:
private void readXML()
XmlDocument xml = new XmlDocument();
// You'll need to put the correct path to your xml file here
xml.Load(Server.MapPath("~/XmlFile11.xml"));
// Select a specific node
XmlNode node = xml.SelectSingleNode("result/data/value");
// Get its value
string name = node.InnerText;
请告诉我如何获得 MailingGUID 值。
谢谢
【问题讨论】:
你在正确的轨道上,问题在于你的 XPath 查询。看看这里:Link 【参考方案1】:更新: 我认为您的架构可能有问题,我删除了对它们的引用并且您的代码运行良好。我试过这个:
const string str = "<?xml version=\"1.0\" encoding=\"utf-8\"?><result><data><key>MailingGUID</key><value>0aa2b2e3-7afa-4002-ab2f-9eb4cbe33ae7</value></data><data><key>OrderRef</key><value>52186</value></data></result>";
var xml = new XmlDocument();
xml.LoadXml(str);
xml.DocumentElement.SelectSingleNode("/result/data/value").InnerText
【讨论】:
XmlNode 节点 = xml.DocumentElement.SelectSingleNode("/result/data"); // 获取它的值 string name = node.InnerText;这给了我对象引用的错误.. 为什么我得到空值。这是代码: private void readXML() XmlDocument xml = new XmlDocument(); xml.Load(Server.MapPath("~/XMLFile1.xml")); var node = xml.DocumentElement.SelectSingleNode("/result/data"); var s = node["value"].InnerText; 尝试调试你的代码,看看你在运行时的特定时间有什么值。 xml.Load 是否有效,加载后您的 xml 变量设置为什么。尝试删除 XSD 引用,看看它是否能解决您的问题(这意味着 XSD 架构存在问题)。 它通过删除 XSD 为我工作。你能告诉我为什么 XSD 文件会产生错误。我必须解决这个 XSD 问题。 我无法告诉您 XSD 出了什么问题。您将不得不打开它们并找到其中的错误。如果您不知道如何自己调试它,您可以使用诸如此类的验证工具来针对您的 XSD 验证您的 XML - freeformatter.com/xml-validator-xsd.html【参考方案2】:import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Parsing of xml is done here
Document doc = builder.parse(new File("C:\\Users\\User_Name\\Documents\\My Received Files\\PDSL_ABM.xml"));
//Here we get the root element of XML and print out
doc.getDocumentElement().normalize();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList list = doc.getElementsByTagName("MailingGUID");
int totalMailingGUID =list.getLength();
System.out.println("Total no of MailingGUID : " + totalSupplierPartID);
//Traversing all the elements from the list and printing out its data
for (int i = 0; i < list.getLength(); i++)
//Getting one node from the list.
Node childNode = list.item(i);
System.out.println("MailingGUID : " + childNode.getTextContent());
【讨论】:
以上是关于java如何读取xml节点元素值?的主要内容,如果未能解决你的问题,请参考以下文章