2016-08-25 21 views
0

xml-stringを別のxml-stringsにタグで分割するにはどうすればよいですか?XMLの文字列をJavaのタグで分割する

次のXMLがあるとします。 のtag1とその値、 のtag2とその値、そして のtag3の値を持つxml-stringを持つにはどうすればいいですか?

<?xml version="1.0"?> 
<Tag0> 
    <Tag1> //Other tags and values for tag1 </Tag1> 
    <Tag2> </Tag2> 
    <Tag3> </Tag3> 
</Tag0>  

私は、XML文字列のXSDを作成するときにそれらの残りの部分はTAG1と同じ名前空間を持っているので、それだけでTAG1のためだけのXSDを作成するので、私はXMLを分割しています。

+3

XMLパーサーを使用していますか? XMLと正規表現は一致しません**:http://stackoverflow.com/questions/8577060/why-is-it-such-a-bad-idea-to-parse-xml-with-regex ...または面白いvesion:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – GhostCat

答えて

3

XMLを解析した後、getElementsByTagNameを呼び出すと、NodeListが返され、NodeListから各要素のNodeオブジェクトがインスタンス化されます。

+0

http://stackoverflow.com/questions/39151102/get-tag-as-the-values-xml/39151192#39151192 –

1

SAXParserを使用して、xmlをJavaオブジェクトに最初に解析します。あなたはそれを使って何かを得ることができます。

1

ここでは、XPathとvtd-xmlで分割するコードを示します。

import com.ximpleware.*; 
import java.io.*; 
public class splitXML { 
    public static void main(String[] args) throws VTDException, IOException { 
     VTDGen vg = new VTDGen(); 
     if (!vg.parseFile("d:\\xml\\input.xml", false)){ 
      System.out.println("error"); 
      return; 
     } 
     VTDNav vn = vg.getNav(); 
     AutoPilot ap = new AutoPilot(vn); 
     ap.selectXPath("/tag0/*"); 
     int i=0,n=0; 
     FileOutputStream fos =null; 
     while((i=ap.evalXPath())!=-1){ 
      fos = new FileOutputStream("d:\\xml\\output"+(++n)+".xml"); 
      long l = vn.getElementFragment(); 
      fos.write(vn.getXML().getBytes(), (int)l, (int)(l>>32)); 
      fos.close(); 
     } 
    } 
}