2011-04-06 4 views
1

다음 XML이 있는데 일부 노드의 값을 인쇄하려고합니다. 예를 들어, 다음 코드를 사용하여 "200812 라이브 bigfish" Java : XML 파일을 구문 분석하는 동안의 문제

내가 무슨 일을하고있는 중이 야 나는

NodeList list = doc.getElementsByTagName("photo"); 
element = (Element)list.item(0); 
list = element.getChildNodes(); 
System.out.println(list.item(0).getNodeName()); 
System.out.println(list.item(0).getNodeValue()); 

을 인쇄 할 내가 대신 "제목"과의

null 
#text 

를 얻을? 감사

<?xml version="1.0" encoding="utf-8" ?> 
<rsp stat="ok"> 
<photo id="2882550369" secret="21054282c8" server="3106" farm="4" dateuploaded="1222202793" isfavorite="0" license="0" safety_level="0" rotation="0" views="5" media="photo"> 
    <owner nsid="[email protected]" username="fishthemusic" realname="masayoshi yamamiya" location="kawasaki, japan" iconserver="4" iconfarm="1" /> 
    <title>bigfish live 200812</title> 
    <description>photo by Kazuhiro Nakamura</description> 
    <visibility ispublic="1" isfriend="0" isfamily="0" /> 
    <dates posted="1222202793" taken="2008-09-24 05:46:33" takengranularity="0" lastupdate="1222998937" /> 
    <editability cancomment="1" canaddmeta="0" /> 
    <publiceditability cancomment="1" canaddmeta="0" /> 
    <usage candownload="1" canblog="1" canprint="0" canshare="1" /> 
    <comments>0</comments> 
    <notes /> 
    <tags> 
     <tag id="314160-2882550369-80673" author="[email protected]" raw="bigfish" machine_tag="0">bigfish</tag> 
     <tag id="314160-2882550369-5558" author="[email protected]" raw="live" machine_tag="0">live</tag> 
     <tag id="314160-2882550369-29726586" author="[email protected]" raw="upcoming:event=1167424" machine_tag="1">upcoming:event=1167424</tag> 
    </tags> 
    <urls> 
     <url type="photopage">http://www.flickr.com/photos/fishthemusic/2882550369/</url> 
    </urls> 
</photo> 
</rsp> 

답변

2

아래의 예에서 XXXX로 표시하여 photo 요소, 텍스트 노드 있습니다. 이 텍스트 노드가 나타납니다. 인접한 텍스트 노드가 여러 개있을 수 있습니다. owner 요소를 얻으려면 요소 유형이있는 첫 번째 노드를 찾아야합니다. 요소가 null 인의 BTW, "nodeValue를"을

NodeList list = doc.getElementsByTagName("photo"); 
element = (Element)list.item(0); 
list = element.getChildNodes(); 

int ix = 0; 
while (ix < list.getLength() && list.item(ix).getNodeType() != Node.ELEMENT_NODE) { 
    ix++; 
} 

// now ix points to your first element node (if there was one) 

System.out.println(list.item(ix).getNodeName()); 
System.out.println(list.item(ix).getNodeValue()); 

을, 그래서 당신은 출력으로

owner 
null 

을 볼 수 :

<photo ...>XXXX 
XXXX<owner nsid="[email protected]" ... /> 

대신 사용해보십시오. 자세한 내용은 http://download.oracle.com/javase/6/docs/api/org/w3c/dom/Node.html을 참조하십시오. (또한 #text이 텍스트 노드의 nodeName이라는 것을 보여줍니다.

0

전화 할 때 element.getChildNodes() 당신이 idsecret 같은 속성을 포함하는 요소의 모든 자식을 얻기 때문이다. 따라서 list.item(0)은 속성이므로 원하는 결과를 얻지 못하는 것입니다.

getNodeName() 반환 null 속성의 값이 차례로 그 속성의 문자열 값을 유지하는 텍스트 노드이기 때문에 속성이없는 노드 이름을
getNodeValue() 반환 #text이 없기 때문입니다.

또한, 완전히 다른 무언가를 다시 사용하기 위해 동일한 변수 (예를 들어, list)를 다시 정의하지 마십시오. 정말 나쁜 습관입니다.

+0

나는 그가 getChildNodes의 속성을 받고있다 생각하지 않는다 작동하지만, 그는 공백 문자 텍스트 노드를 받고있다. –

+0

XML은'<[[CDATA]]>' –

+0

@Travis 안에 있지 않으면 공백을 무시합니다. 그건 사실이 아닙니다. 우선 DOM의 Element 노드의 애트리뷰트는 아닌 것으로 간주되며 두 번째로 공백은 기본적으로 무시되지 않습니다. CDATA는 문법적인 설탕 일 뿐이며 공백과는 특별한 관계가 없습니다. –

-1

SAX/DOM 대신 JAXB를 사용하면이 로켓 과학을 훨씬 쉽게 만들 수 있습니다. 설명은 this article을 참조하십시오.

첫째, 해당 XSD 스키마를 (당신이 원하지 않는 노드를 생략 할 수 있습니다) 쓰기; http://mojo.codehaus.org/jaxb2-maven-plugin/usage.html :

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:element name="photo"> 
     <xsd:complexType> 
      <xsd:sequence> 
       <xsd:element name="owner" type="owner" /> 
       <xsd:element name="title" type="xsd:string" /> 
      </xsd:sequence> 
      <xsd:attribute name="id" type="xsd:int" /> 
      <xsd:attribute name="secret" type="xsd:string" /> 
     </xsd:complexType> 
    </xsd:element> 

    <xsd:complexType name="owner"> 
     <xsd:attribute name="nsid" type="xsd:string" /> 
    </xsd:complexType> 
</xsd:schema> 

이 두 번째로,이 받는다는 플러그인을 사용하여이에서 클래스를 생성 : 여기에 좋은 시작이다.

그런 다음 코드를 작성 (그리고 프로젝트에 JAXB maven dependency 추가) :

public class JaxbTest { 
    @Test 
    public void should_parse_recipe() throws JAXBException { 
     URL xmlUrl = Resources.getResource("file.xml"); 
     Photo recipe = parse(xmlUrl, Photo.class); 
     assertEquals(Integer.valueOf(15), recipe.getCooking().getDuration()); 
    } 

    private <T> T parse(URL url, Class<T> clazz) throws JAXBException { 
     Unmarshaller unmarsh = JAXBContext.newInstance(clazz).createUnmarshaller(); 
     return clazz.cast(unmarsh.unmarshal(url)); 
    } 
} 

추신. Resources.getResource은 구아바 출신입니다. 는 Thread.currentThread(). getContextClassLoader(). 인 getSystemResource ("file.xml")를 사용하는 대신

관련 문제