import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class ReadXMLStaff {
public static void main(String[] args) {
try {
File fXmlFile = new File("FXML.xml");
DocumentBuilder dBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=dBuilder.parse(fXmlFile);
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
if (doc.hasChildNodes()) {
pierceTheNode(doc.getChildNodes());
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void pierceTheNode(NodeList nList){
for(int i=0; i<nList.getLength(); i++){
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if(node.hasChildNodes()){
pierceTheNode(node.getChildNodes());
}
if(!node.getTextContent().contains(" ")){
System.out.print("Name :: "+node.getNodeName());
System.out.println(" Value :: "+node.getTextContent());
}
}
}
}
}
Output ออกมาแบบนี้ Code
Root element :Rq
Name :: RqID Value :: 1
Name :: MsgCd Value :: RDSWACMG
Name :: TrTp Value :: NW
Name :: Hdr Value ::
1
RDSWACMG
NW
Name :: PtyNo Value :: 555
Name :: AcCd Value :: AAA001
Name :: AcNm Value :: AAA001
Name :: AcSts Value :: A
Name :: AcTp Value :: C
Name :: AcMrgTp Value :: N
Name :: InvTp Value :: C
Name :: AtMOYn Value :: N
Name :: ClildTp Value :: N
Name :: Clild Value :: 1234567890123
Name :: MMYn Value :: N
Name :: BthDt Value :: 1980-01-01
Name :: CtryCd Value ::
Name :: Adr1 Value ::
Name :: Adr2 Value ::
Name :: Adr3 Value ::
Name :: AdrState Value ::
Name :: AdrCtry Value ::
Name :: ZipCd Value ::
Name :: HomTelCtry Value ::
Name :: HomTelArea Value ::
Name :: HomTelNo Value ::
Name :: OfcTelCtry Value ::
Name :: OfcTelArea Value ::
Name :: OfcTelNo Value ::
Name :: MblTelCtry Value ::
Name :: MblTelArea Value ::
Name :: MblTelNo Value ::
Name :: Email Value ::
Name :: Bdy Value ::
555
AAA001
AAA001
A
C
N
C
N
N
1234567890123
N
1980-01-01
ที่จริงอยากให้เป็นแบบนี้ Code
Root element :Rq
Name :: RqID Value :: 1
Name :: MsgCd Value :: RDSWACMG
Name :: TrTp Value :: NW
Name :: PtyNo Value :: 555
Name :: AcCd Value :: AAA001
Name :: AcNm Value :: AAA001
Name :: AcSts Value :: A
Name :: AcTp Value :: C
Name :: AcMrgTp Value :: N
Name :: InvTp Value :: C
Name :: AtMOYn Value :: N
Name :: ClildTp Value :: N
Name :: Clild Value :: 1234567890123
Name :: MMYn Value :: N
Name :: BthDt Value :: 1980-01-01
Name :: CtryCd Value ::
Name :: Adr1 Value ::
Name :: Adr2 Value ::
Name :: Adr3 Value ::
Name :: AdrState Value ::
Name :: AdrCtry Value ::
Name :: ZipCd Value ::
Name :: HomTelCtry Value ::
Name :: HomTelArea Value ::
Name :: HomTelNo Value ::
Name :: OfcTelCtry Value ::
Name :: OfcTelArea Value ::
Name :: OfcTelNo Value ::
Name :: MblTelCtry Value ::
Name :: MblTelArea Value ::
Name :: MblTelNo Value ::
Name :: Email Value ::