- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 XML 文件,我想使用 SAX 从中获取数据。它一直持续到 startElement() 为止,出现错误,因为当我尝试获取属性值时,这些属性值为 null。为什么?
首先,我称这个方法为:load()
public RealEstate load() {
RealEstate data = null;
try {
//Create a "parser factory" for creating SAX parsers
SAXParserFactory spfac = SAXParserFactory.newInstance();
//Now use the parser factory to create a SAXParser object
SAXParser sp = spfac.newSAXParser();
XMLReader xmlReader = sp.getXMLReader();
//Create an instance of this class; it defines all the handler methods
SaxParserRealEstateHandler handler = new SaxParserRealEstateHandler();
//assign our handler
xmlReader.setContentHandler(handler);
// Convert file to URL.
URL url = handler.fileToURL(new File(xmlFilename));
// Parse file.
xmlReader.parse(url.toString());
data = handler.getData();
} catch (ParserConfigurationException ex) {
Logger.getLogger(RealStatePersistXML.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SAXException ex) {
Logger.getLogger(RealStatePersistXML.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(RealStatePersistXML.class.getName()).log(Level.SEVERE, null, ex);
}
return data;
}
这里有方法startElement和endElement。
class SaxParserRealEstateHandler extends DefaultHandler
{
private String temp;
private RealEstate data;
private Estate estate;
private estateAddress address;
/**
* CONSTRUCTOR
*/
public SaxParserRealEstateHandler()
{
}
/**
* getData()
* This method gets the list of estates from RealEstate class.
* @return data list of states. Null in case of error or list not found.
*/
public RealEstate getData()
{
// RealEstate data = new RealEstate();
// data.addEstate(estate);
// data.getEstates();
// return data;
}
/*
* When the parser encounters plain text (not XML elements),
* it calls(this method, which accumulates them in a string buffer
*/
public void characters(char[] buffer, int start, int length) {
temp = new String(buffer, start, length);
}
/*
* Every time the parser encounters the beginning of a new element,
* it calls this method, which resets the string buffer
*/
public void startElement(String uri, String localName, String qName, Attributes attributes){
switch (qName){
case"realState":
data = new RealEstate();
break;
case"estate":
estate = new Estate();
estate.setType(attributes.getValue("type"));
estate.setSurface(Double.parseDouble(attributes.getValue("surface")));
//estate.setAddress(attributes.getValue("address"));
estate.setPrice(Integer.parseInt(attributes.getValue("price")));
break;
case"address":
address = new estateAddress();
address.setStreet(attributes.getValue("type"));
address.setNumber(Integer.parseInt(attributes.getValue("surface")));
address.setFloor(Integer.parseInt(attributes.getValue("type")));
address.setDoor(Integer.parseInt(attributes.getValue("surface")));
break;
default:
break;
}
}
public void endElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch (qName){
case"estate":
data.getEstates().add(estate);//quant ha llegit la etiqueta (</estate>) l'agreguem
break;
case"surface":
double surface = Double.parseDouble(temp);
estate.setSurface(surface);
break;
case"price":
double price = Double.parseDouble(temp);//tractar tema errors del parseDouble!
estate.setPrice(price);
break;
case"address":
estate.setAddress(address);
break;
case"street":
address.setStreet(temp);
break;
case"number":
int number = Integer.parseInt(temp);
address.setNumber(number);
break;
case"floor":
address.setStreet(temp);
break;
case"door":
address.setStreet(temp);
break;
default:
break;
}
}
/** fileToURL()
* Convenience method to convert a file to a url
* @throws Error if malformed url exception is generated
*/
public URL fileToURL(File file)
{
String path = file.getAbsolutePath();
String fSep = System.getProperty("file.separator");
if (fSep != null && fSep.length() == 1)
path = path.replace(fSep.charAt(0), '/');
if (path.length() > 0 && path.charAt(0) != '/')
path = '/' + path;
try
{
return new URL("file", null, path);
}
catch (java.net.MalformedURLException e)
{
throw new Error("Unexpected MalformedURLException");//no he pogut muntar una url com deu mana
//retornar null
}
}
}
XML 代码
<?xml version="1.0" encoding="UTF-8"?>
<realState xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="realState.xsd">
<estate>
<type>House</type>
<surface>250,0</surface>
<address>
<street>C/Tarragona</street>
<number>54</number>
<floor>2</floor>
<door>1</door>
</address>
<price>140000,0</price>
</estate>
</realState>
XSD 代码:http://pastebin.com/nzEDsdLg
类 RealEstate 和 Estate 工作正常!
谢谢!
最佳答案
type
, surface
,和price
不是 <estate>
的属性元素。它们是子元素。
作为属性,您的 XML 应该是:
<estate type="House" surface="250,0" price="140000,0">
<address>
<street>C/Tarragona</street>
<number>54</number>
<floor>2</floor>
<door>1</door>
</address>
</estate>
使用 StAX 解析器比 SAX 解析器容易得多,并且具有非常相似的性能特征,因此我建议您改用它。
关于Java - SAXParser 和 XMLReader 获取 null 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36211271/
我想将使用 .Net Compact Framework 3.5 制作的 Windows Mobile 应用程序降级到 .Net Compact Framework 2.0 SP2。 但是...我不知
我正在尝试从 xml 字符串中读取但是, ` XmlReader reader=XmlReader.Create(new StringReader(stringXml)` 读者总是没有。为什么没有
在以下代码段中,当我遇到一个元素时,使用 XmlReader。我想按原样阅读它,包括元素中的所有属性和命名空间装饰。使用 oXml.Name 属性,我只能获取标签名称。是否有获取标签本身的功能? oX
这可能是一个关于 XmlReader 的幼稚问题,但我还没有在 MSDN 文档中找到答案。 假设我有 XSD SchemaTest.xsd
我想做这样的事情: stringBuilder.AppendLine(" globalVar." + reader.GetAttribute(i).Name + " = " + reader[i]
使用 XMLReader 方法解析 XML 文件时,如何获取元素的父节点? $xml = new XMLReader(); $xml->XML($xmlString); while($xml->rea
这很奇怪。我有一个 WCF Message我正在尝试将正文的内容读入 XmlDocument。消息正文的内容在网络上看起来像这样(在打开 WCF 跟踪的情况下进行检查): (GMT-05:0
我有一个 Xml 文档,其中一些元素如下所示: W X Y Z ABC 我的目标是从上面的例子中得到“ABC”。我尝试查看 XmlElement 类中的 InnerText(返回“WXYZABC”
我有以下代码: for (i = 1; i <= loopsNeeded; i++) { lblCurrent.Text = string.Format("{0} of
我正在尝试将 xml 加载到 XDocument 对象中。 public void ValidateRules(XmlReader xml) { xml.MoveToContent();
我必须为我的商店解析 3 个远程 XML 文件(产品、价格、类别),其中最大的大约有 500MB+。我必须解析它们并插入到 mysql 数据库中。 我可以从两种格式中选择 所有 3 个 XML 文件压
我正在尝试使用 XMLReader ( https://github.com/amarcadet/XMLReader ) 在 objective-c 中制作一个将解析 xml 文档的应用程序:
代码如下: string str = "AppleMango"; using (XmlReader xmlReader = XmlReader.Create(new StringReader(str)
我了解我们如何使用如下代码示例.. public class Sample { public static void Main() { using (XmlReader
我正在使用 XmlReader 读取非常大的 XML 文件(超过 6GB 的数据)以加快一切速度并且工作得非常好。 我在另一个线程中执行此操作(不使用后台工作程序)并且我不知道如何更新进度条,因为 X
关注此introduction可以通过导入命名空间 System.Xml 来使用 XMLReader 类。在我的 Visual Studio 项目中,我使用 .NET 4.0,但 System.Xml
我正在使用以下代码使用 XmlReader 读取一些 XML: XmlReaderSettings settings = new XmlReaderSettings(); settings.Valid
好的,所以我有这个 XML 文件: Iron Repeater true 19 19 50 18 1 1 5 39
为什么我应该将 XMLReader 与 SAXParser 一起使用?我经常看到这种用法: sp = spf.newSAXParser(); XMLReader xr
我有这个 xml 文件。 8.582207 3 true
我是一名优秀的程序员,十分优秀!