Java 从SAX当前元素中提取属性?
我必须使用Java 从SAX当前元素中提取属性?,java,xml,xml-parsing,xsd,saxparser,Java,Xml,Xml Parsing,Xsd,Saxparser,我必须使用xsd验证来解析xml文件。我只想到一点,却找不到解决办法 以下是xml文件loooks的工作方式: <?xml version="1.0" encoding="UTF-8"?> <staff xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="newEmployee.
xsd
验证来解析xml
文件。我只想到一点,却找不到解决办法
以下是xml文件loooks的工作方式:
<?xml version="1.0" encoding="UTF-8"?>
<staff xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="newEmployee.xsd">
<employee>
<name>Carl Cracker</name>
<salary>75000</salary>
<hiredate year="1987" month="12" day="15" />
</employee>
<employee>
<name>Harry Hacker</name>
<salary>50000</salary>
<hiredate year="1989" month="10" day="1" />
</employee>
<employee>
<name>Tony Tester</name>
<salary>40000</salary>
<hiredate year="1990" month="3" day="15" />
</employee>
</staff>
卡尔·克莱克
75000
哈利·哈克
50000
托尼测试仪
40000
xsd验证:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="staff">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="employee" maxOccurs="unbounded" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="employee">
<xsd:complexType>
<xsd:sequence>
<xsd:element type="xsd:string" name="name"/>
<xsd:element type="xsd:int" name="salary"/>
<xsd:element name="hiredate">
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute type="xsd:short" name="year" use="optional"/>
<xsd:attribute type="xsd:byte" name="month" use="optional"/>
<xsd:attribute type="xsd:byte" name="day" use="optional"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
我和你核对过了。一切都是正确的
以下是我的代码片段:
public class SaxParserDemo {
public static void main(String[] args) {
Schema schema;
String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
SchemaFactory schemaFactory = SchemaFactory.newInstance(language);
try {
schema = schemaFactory.newSchema(new File(EMPLOYEE_XSD.getFilename())); // create new xml schema
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setSchema(schema); // set schema to the factory
InputStream xmlInput = new FileInputStream(EMPLOYEE_XML.getFilename());
SAXParser saxParser = factory.newSAXParser();
SaxHandler handler = new SaxHandler();
saxParser.parse(xmlInput, handler);
for (Employee employee : handler.employees) {
System.out.println(employee);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
class SaxHandler extends DefaultHandler {
private Stack<String> elementStack = new Stack<>();
private Stack<Object> objectStack = new Stack<>();
public List<Employee> employees = new ArrayList<>();
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
this.elementStack.push(qName);
if ("employee".equals(qName)) {
Employee employee = new Employee();
this.objectStack.push(employee);
this.employees.add(employee);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
this.elementStack.pop();
if ("employee".equals(qName)) {
Object objects = this.objectStack.pop();
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String value = new String(ch, start, length).trim();
if (value.length() == 0) return; // skip white space
if ("name".equals(currentElement())) {
Employee employee = (Employee) this.objectStack.peek();
employee.setName(value);
} else if ("salary".equals(currentElement()) && "employee".equals(currentParrentElement())) {
Employee employee = new Employee();
employee.setSalary(Double.parseDouble(value));
} else if ("hiredate".equals(currentElement()) && "employee".equals(currentParrentElement())) {
Employee employee = new Employee();
// I stuck here
// employee.setHireDay();
}
}
private String currentElement() {
return this.elementStack.peek();
}
private String currentParrentElement() {
if (this.elementStack.size() < 2) return null;
return this.elementStack.get(this.elementStack.size() - 2);
}
}
公共类SaxParserDemo{
公共静态void main(字符串[]args){
图式;
String language=xmlstants.W3C\u XML\u SCHEMA\u NS\u URI;
SchemaFactory SchemaFactory=SchemaFactory.newInstance(语言);
试一试{
schema=schemaFactory.newSchema(新文件(EMPLOYEE_XSD.getFilename());//创建新的xml模式
SAXParserFactory=SAXParserFactory.newInstance();
setSchema(schema);//将schema设置为工厂
InputStream xmlInput=新文件InputStream(EMPLOYEE_XML.getFilename());
SAXParser SAXParser=factory.newSAXParser();
SaxHandler=新SaxHandler();
parse(xmlInput,handler);
for(员工:handler.employees){
系统输出打印项次(员工);
}
}捕获(可丢弃的e){
e、 printStackTrace();
}
}
}
类SaxHandler扩展了DefaultHandler{
私有堆栈元素Stack=新堆栈();
私有堆栈objectStack=新堆栈();
public List employees=new ArrayList();
@凌驾
public void startElement(字符串uri、字符串localName、字符串qName、属性)引发SAXException{
this.elementStack.push(qName);
如果(“雇员”。等于(qName)){
员工=新员工();
this.objectStack.push(employee);
this.employees.add(employee);
}
}
@凌驾
public void endElement(字符串uri、字符串localName、字符串qName)引发SAXException{
this.elementStack.pop();
如果(“雇员”。等于(qName)){
Object objects=this.objectStack.pop();
}
}
@凌驾
公共无效字符(char[]ch,int start,int length)引发异常{
字符串值=新字符串(ch,start,length).trim();
if(value.length()==0)返回;//跳过空白
if(“name”.equals(currentElement())){
Employee=(Employee)this.objectStack.peek();
employee.setName(值);
}如果(“salary.equals(currentElement())&&“employee.equals(currentParrentElement())”,则为{
员工=新员工();
employee.setSalary(Double.parseDouble(value));
}否则如果(“hiredate.equals(currentElement())&“employee.equals(currentParrentElement())){
员工=新员工();
//我被困在这里
//employee.setHireDay();
}
}
私有字符串currentElement(){
返回此.elementStack.peek();
}
私有字符串currentParrentElement(){
if(this.elementStack.size()<2)返回null;
返回this.elementStack.get(this.elementStack.size()-2);
}
}
我必须从元素属性中提取数据。我不知道如何实现它。我第一次使用SAX。有什么建议吗
Employees类有两个用于hireday的setter:
setHireDay(日期hireDay)
setHireDay(整数年、整数月、整数日)
如何解决这个问题?像这样:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Stack;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxParserDemo {
public static void main(String[] args) {
Schema schema;
String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
SchemaFactory schemaFactory = SchemaFactory.newInstance(language);
try {
schema = schemaFactory.newSchema(new File("src/newEmployee.xsd")); // create new xml schema
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setSchema(schema); // set schema to the factory
InputStream xmlInput = new FileInputStream("src/empl.xml");
SAXParser saxParser = factory.newSAXParser();
SaxHandler handler = new SaxHandler();
saxParser.parse(xmlInput, handler);
for (Employee employee : handler.employees) {
System.out.println(employee.getName());
System.out.println(employee.getSalary());
System.out.println(employee.getHireDate());
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
class SaxHandler extends DefaultHandler {
private Stack<String> elementStack = new Stack<String>();
private Stack<Object> objectStack = new Stack<Object>();
public List<Employee> employees = new ArrayList<Employee>();
Employee employee=null;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
this.elementStack.push(qName);
if ("employee".equals(qName)) {
if (employee!=null) {
this.employees.add(employee);
}
employee = new Employee();
this.objectStack.push(employee);
}
if ("hiredate".equals(qName)) {
String yearatt=attributes.getValue("year");
System.out.println(yearatt);
String monthatt=attributes.getValue("month");
System.out.println(monthatt);
String dayatt=attributes.getValue("day");
System.out.println(dayatt);
employee.setHireDay( yearatt, monthatt, dayatt) ;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
this.elementStack.pop();
if ("employee".equals(qName)) {
Object objects = this.objectStack.pop();
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String value = new String(ch, start, length).trim();
if (value.length() == 0) return; // skip white space
if ("name".equals(currentElement())) {
employee = (Employee) this.objectStack.peek();
employee.setName(value);
} else if ("salary".equals(currentElement()) && "employee".equals(currentParrentElement())) {
employee.setSalary(Double.parseDouble(value));
} else if ("hiredate".equals(currentElement()) && "employee".equals(currentParrentElement())) {
// I stuck here
// employee.setHireDay();
}
}
private String currentElement() {
return this.elementStack.peek();
}
private String currentParrentElement() {
if (this.elementStack.size() < 2) return null;
return this.elementStack.get(this.elementStack.size() - 2);
}
}
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.InputStream;
导入java.util.ArrayList;
导入java.util.Date;
导入java.util.List;
导入java.util.Stack;
导入javax.xml.xmlstants;
导入javax.xml.parsers.SAXParser;
导入javax.xml.parsers.SAXParserFactory;
导入javax.xml.validation.Schema;
导入javax.xml.validation.SchemaFactory;
导入org.xml.sax.Attributes;
导入org.xml.sax.SAXException;
导入org.xml.sax.helpers.DefaultHandler;
公共类SaxParserDemo{
公共静态void main(字符串[]args){
图式;
String language=xmlstants.W3C\u XML\u SCHEMA\u NS\u URI;
SchemaFactory SchemaFactory=SchemaFactory.newInstance(语言);
试一试{
schema=schemaFactory.newSchema(新文件(“src/newEmployee.xsd”);//创建新的xml模式
SAXParserFactory=SAXParserFactory.newInstance();
setSchema(schema);//将schema设置为工厂
InputStream xmlInput=新文件InputStream(“src/emp.xml”);
SAXParser SAXParser=factory.newSAXParser();
SaxHandler=新SaxHandler();
parse(xmlInput,handler);
for(员工:handler.employees){
System.out.println(employee.getName());
System.out.println(employee.getSalary());
System.out.println(employee.getHireDate());
}
}捕获(可丢弃的e){
e、 printStackTrace();
}
}
}
类SaxHandler扩展了DefaultHandler{
私有堆栈元素Stack=新堆栈();
私有堆栈objectStack=新堆栈();
public List employees=new ArrayList();
Employee=null;
@凌驾
public void startElement(字符串uri、字符串localName、字符串qName、属性)引发SAXException{
这是.elementStack。