이것은 나에게조차도 어리석은 질문처럼 보일 수 있지만 대답을 찾을 수없는 질문 중 하나입니다.STax를 사용하여 Java에서 XML 구문 분석
임과 같은 모습을 구문 분석하려고 자바 STAX를 사용하여 XML과 XML 메신저를 구문 분석하려고 -
<?xml version="1.0" encoding="UTF-8"?>
<Macros>
<MacroDefinition>
<MacroName>
<string>Macro1</string>
</MacroName>
</MacroDefinition>
</Macros>
다음과 같이 지금은 매크로 클래스가 -
public class Macro {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
나는 또한 XML을 'Macro'클래스의 객체로 변환하려고하는 파서 클래스를 사용한다.
public class StaxParser {
static final String MACRODEFINITION = "MacroDefinition";
static final String MACRONAME = "MacroName";
static final String STRING = "string";
@SuppressWarnings({ "unchecked", "null" })
public List<Item> readMacro(String configFile) {
List<Macro> macroList = new ArrayList<Macro>();
try {
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
InputStream in = new FileInputStream(configFile);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document
Macro macro = null;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
if (startElement.getName().getLocalPart() == (MACRODEFINITION)) {
macro = new Macro();
}
if (event.isStartElement()) {
if (event.asStartElement().getName().getLocalPart()
.equals(MACRONAME)) {
Iterator<Attribute> attributes = event
.asStartElement().getAttributes();
while (attributes.hasNext()) {
Attribute attribute = attributes.next();
if (attribute.getName().toString()
.equals(STRING)) {
macro.setMacroName(event.asCharacters()
.getData());
}
}
event = eventReader.nextEvent();
continue;
}
}
}
// If we reach the end of an item element we add it to the list
if (event.isEndElement()) {
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart() == (MACRODEFINITION)) {
macroList.add(macro);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
return macroList;
}
}
문제 메신저 직면 파서가 '매크로 이름'의 자식 노드를 읽을 수 없다는 것이다 - 다음과 같이 파서 클래스 조각입니다. 내 생각에 getAttributes
은 작동하지 않게되지만 어떤 특정 노드의 자식 노드를 가져 오기 위해 어떤 메서드를 호출해야하는지에 대한 단서가 없습니다.
이에 대한 도움을 주시면 대단히 감사하겠습니다.
감사
p1nG
나는 인정해야한다. 이 코드 스 니펫에서 무엇을하고 있는지 파악하는 데는 시간이 걸렸지 만 지금까지 StAX를 사용하여 xml을 구문 분석 한 적이 있습니다. – Nerrve