2012-03-18 2 views
7

XML 파일이 있고 그 요소에도 속성이 있습니다. 텍스트 파일의 요소 값을 구문 분석하고 인쇄하지만 요소 속성 값은 인쇄하지 않는 간단한 Java 파일이 있습니다. 속성 값을 인쇄하는 데 도움을주십시오. 나는 아래의 코드를 붙여 오전 : -------- employees.xml 파일을 -----------Java를 사용하여 요소 값 및 속성 값을 가져 오는 XML 구문 분석

<?xml version="1.0" encoding="UTF-8"?> 

<Personnel> 

    <Employee type="permanent"> 
    <Name>Seagull</Name> 
    <Id>3674</Id> 
    <Age>34</Age> 
    </Employee> 

    <Employee type="contract"> 
    <Name>Robin</Name> 
    <Id>3675</Id> 
    <Age>25</Age> 
</Employee> 

    <Employee type="permanent"> 
    <Name>Crow</Name> 
    <Id>3676</Id> 
    <Age>28</Age> 
    </Employee> 

</Personnel> 

----------- ----------------- StoreData.java ------------------------------ -----------

당신은 다음과 같은 사용할 수 org.w3c.dom의 사용하고 있기 때문에
import java.io.*; 
import org.w3c.dom.*; 
import org.xml.sax.*; 
import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

public class StoreData{ 
static public void main(String[] arg) { 
    try{ 
     BufferedReader bf = new BufferedReader(new  InputStreamReader(System.in)); 
     System.out.print("Enter XML file name: "); 
     String xmlFile = bf.readLine(); 
     File file = new File(xmlFile); 
      if (file.exists()){ 
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder builder = factory.newDocumentBuilder(); 
      Document doc = builder.parse(xmlFile); 
         //Create transformer 
      Transformer tFormer = TransformerFactory.newInstance().newTransformer(); 
        //Output Types (text/xml/html) 
      tFormer.setOutputProperty(OutputKeys.METHOD, "text"); 
//    Write the document to a file 
      Source source = new DOMSource(doc); 
//    Create File  to view your xml data as (vk.txt/vk.doc/vk.xls/vk.shtml/vk.html) 
      Result result = new StreamResult(new File("file.txt")); 
      tFormer.transform(source, result); 
      System.out.println("File creation successfully!"); 
     } 
     else{ 
      System.out.println("File not found!"); 
     } 
    } 
    catch (Exception e){ 
     System.err.println(e); 
     System.exit(0); 
    } 
} } 

+0

이 링크를 참조 http://stackoverflow.com/questions/9781568/update-data-in-java-class-as -per-change-in-the-XML-file/9783154 # 9783154 –

답변

1

:

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     InputSource is = new InputSource(new StringReader(xmlFile)); 
     Document doc = builder.parse(is); 

     NodeList nodeList = doc.getElementsByTagName("Employee"); 

     for (int i = 0; i < nodeList.getLength(); i++) {     
      Node node = nodeList.item(i); 

      if (node.hasAttributes()) { 
       Attr attr = (Attr) node.getAttributes().getNamedItem("type"); 
       if (attr != null) { 
        String attribute= attr.getValue();      
        System.out.println("attribute: " + attribute);      
       } 
      } 
     } 
1

W를 모자는 기본적으로 요소 텍스트로 변환되는 XSLT 변환입니다. 같은 기술을 사용하여

은, 하나는 자신의 "스타일"을 필요 :

InputStream xsltIn = StoreData.class.getResourceAsStream("/employees.xslt"); 
    StreamSource xslt = new StreamSource(xsltIn); 
    ///StreamSource xslt = new StreamSource(".../employees.xslt"); 

    Transformer tFormer = TransformerFactory.newInstance().newTransformer(xslt); 
나는 자원이 아닌 파일 시스템 파일을 사용 위

때문에이 응용 프로그램과 함께 포장됩니다.

employees.xslt :

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:template match="/Personnel"> 
Personnel: 
     <xsl:apply-templates select="./*"/> 
End personnel. 
    </xsl:template> 

    <xsl:template match="Employee"> 
* Employee:<xsl:apply-templates select="./@*|./*"/> 

    </xsl:template> 

    <xsl:template match="Name|Id|Age|@type"> 
    - <xsl:value-of select="name()"/>: <xsl:value-of select="."/> 
    </xsl:template> 
</xsl:stylesheet> 

생산하는 것 :

Personnel: 

* Employee: 
    - type: permanent 
    - Name: Seagull 
    - Id: 3674 
    - Age: 34 
* Employee: 
    - type: contract 
    - Name: Robin 
    - Id: 3675 
    - Age: 25 
* Employee: 
    - type: permanent 
    - Name: Crow 
    - Id: 3676 
    - Age: 28 
End personnel. 
관련 문제