2016-05-20 21 views
3

次のxml文字列からxmlns属性を削除します。私はjavaプログラムを書いていますが、ここで何が行われる必要があるかどうかはわかりません。xmlとjavaのルート要素からxmlns属性を削除するには

xmlns属性を削除して修正したxml文字列を取得するにはどうすればよいですか?

入力XML文字列:

<?xml version="1.0" encoding="UTF-8"?> 
<Payment xmlns="http://api.com/schema/store/1.0"> 
    <Store>abc</Store> 
</Payment> 

予想されるXML出力文字列:

<?xml version="1.0" encoding="UTF-8"?> 
<Payment> 
    <Store>abc</Store> 
</Payment> 

Javaクラス:

public class XPathUtils { 

    public static void main(String[] args) { 
     String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"http://api.com/schema/store/1.0\"><Store>abc</Store></Payment>"; 
     String afterNsRemoval = removeNameSpace(xml); 
     System.out.println("afterNsRemoval = " + afterNsRemoval); 
    } 

    public static String removeNameSpace(String xml) { 
     try { 
      System.out.println("before xml = " + xml); 
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder builder = factory.newDocumentBuilder(); 
      InputSource inputSource = new InputSource(new StringReader(xml)); 
      Document xmlDoc = builder.parse(inputSource); 
      Node root = xmlDoc.getDocumentElement(); 
      NodeList rootchildren = root.getChildNodes(); 
      Element newroot = xmlDoc.createElement(root.getNodeName()); 
      for (int i = 0; i < rootchildren.getLength(); i++) { 
       newroot.appendChild(rootchildren.item(i).cloneNode(true)); 
      } 
      xmlDoc.replaceChild(newroot, root); 
      return xmlDoc.toString(); 
     } catch (Exception e) { 
      System.out.println("Could not parse message as xml: " + e.getMessage()); 
     } 
     return ""; 
    } 
} 

出力:

before xml = <?xml version="1.0" encoding="UTF-8"?><Payment xmlns="http://api.com/schema/store/1.0"><Store>abc</Store></Payment> 

afterNsRemoval = [#document: null] 
+0

... –

+0

私はそれを試してみるよりも幸せになります。どのようにこれを実装することができますか? – user2325154

+0

gimme数分... xpathの美しさは、選択したすべての属性を効果的に削除することができるということです。非常に複雑な文書の場合でも... xpathは "// @ *"以上です –

答えて

1

import com.ximpleware.*; 
import java.io.*; 

public class removeAttrNode { 
    public static void main(String[] s) throws VTDException, Exception{ 
     VTDGen vg = new VTDGen(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"http://api.com/schema/store/1.0\"><Store>abc</Store></Payment>"; 
     vg.setDoc(xml.getBytes()); 
     vg.parse(false); // turn off namespace awareness so that 
     VTDNav vn = vg.getNav(); 
     AutoPilot ap = new AutoPilot(vn); 
     XMLModifier xm = new XMLModifier(vn); 
     ap.selectXPath("//@xmlns"); 
     int i=0; 
     while((i=ap.evalXPath())!=-1){ 
      xm.remove(); 
     } 
     xm.output(baos); 
     System.out.println(baos.toString());  
    } 
} 
+0

'com.ximpleware'はmvnリポジトリでサードパーティのlibを利用できますか? – user2325154

+0

はい、sourceforgeでも同様です。http://vtd-xml.sf.net –

+1

このような単純なユースケースを解決するためにサードパーティ製のライブラリを使用したいと思っていますか? – SomeDude

2

トランスが必要です。修正方法下のチェック:

public static String removeNameSpace(String xml) { 


     try { 
      TransformerFactory tf = TransformerFactory.newInstance(); 
      Transformer transformer = tf.newTransformer(); 
      transformer.setOutputProperty(OutputKeys.METHOD, "xml"); 
      transformer.setOutputProperty(OutputKeys.INDENT, "false"); 
      System.out.println("before xml = " + xml); 
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder builder = factory.newDocumentBuilder(); 
      InputSource inputSource = new InputSource(new StringReader(xml)); 
      Document xmlDoc = builder.parse(inputSource); 
      Node root = xmlDoc.getDocumentElement(); 
      NodeList rootchildren = root.getChildNodes(); 
      Element newroot = xmlDoc.createElement(root.getNodeName()); 
      for (int i = 0; i < rootchildren.getLength(); i++) { 
       newroot.appendChild(rootchildren.item(i).cloneNode(true)); 
      } 
      xmlDoc.replaceChild(newroot, root); 
      DOMSource requestXMLSource = new DOMSource(xmlDoc.getDocumentElement()); 
      StringWriter requestXMLStringWriter = new StringWriter(); 
      StreamResult requestXMLStreamResult = new StreamResult(requestXMLStringWriter);    
      transformer.transform(requestXMLSource, requestXMLStreamResult); 
      String modifiedRequestXML = requestXMLStringWriter.toString(); 

      return modifiedRequestXML; 
     } catch (Exception e) { 
      System.out.println("Could not parse message as xml: " + e.getMessage()); 
     } 
     return ""; 
    } 

出力:

before xml = <?xml version="1.0" encoding="UTF-8"?><Payment xmlns="http://api.com/schema/store/1.0"><Store>abc</Store></Payment> 
afterNsRemoval = <?xml version="1.0" encoding="UTF-8"?><Payment><Store>abc</Store></Payment> 
+0

DOMコードは私にはちょっと醜いものだと確信しています... –

+0

いつも簡潔にすることができます。 – SomeDude

1

あなたは右の最後のアクション以外のすべてを行っている:それはDocumentオブジェクトの文字列XML表現を生成する間違った方法ですのでdocument.toString()は、あなたが間違った結果が得られます。このanswerを参照してください、それはこの方法の正しい実装含まれています...これは、コードは、XPathとVTD-XML(うち、私は作者午前)でそれを行うことです

public static String toString(Document doc) { 
    try { 
     StringWriter sw = new StringWriter(); 
     TransformerFactory tf = TransformerFactory.newInstance(); 
     ... 
0

XSLTを宣言された/宣言されていない名前空間を削除することは通常の作業です。ベースJavaにはXSLT 1.0プロセッサが搭載されているため、サードパーティのモジュールは必要ありません。さらに、XSLTが変換を処理するので、ループやXMLタグ/属性の再作成は処理されません。

あなたは属性ノードに対処を助けるために... VTD-XMLにこのタスクは短いコードの10行有効なXPath式を使用していないのはなぜ
import java.io.*; 

import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 
import javax.xml.transform.stream.StreamSource; 

import org.w3c.dom.Document; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 

public class XPathUtils { 
    public static void main(String[] args) { 

     String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"http://api.com/schema/store/1.0\"><Store>abc</Store></Payment>"; 
     String afterNsRemoval = removeNameSpace(xml); 
     System.out.println("afterNsRemoval = " + afterNsRemoval); 
    } 

    public static String removeNameSpace(String xml) { 
     try{ 
      String xslStr = String.join("\n", 
       "<xsl:transform xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">", 
       "<xsl:output version=\"1.0\" encoding=\"UTF-8\" indent=\"no\"/>", 
       "<xsl:strip-space elements=\"*\"/>",       
       " <xsl:template match=\"@*|node()\">", 
       " <xsl:element name=\"{local-name()}\">", 
       "  <xsl:apply-templates select=\"@*|node()\"/>", 
       " </xsl:element>", 
       " </xsl:template>", 
       " <xsl:template match=\"text()\">", 
       " <xsl:copy/>", 
       " </xsl:template>",         
       "</xsl:transform>"); 

      // Parse XML and Build Document 
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
      InputSource is = new InputSource(); 
      is.setCharacterStream(new StringReader(xml)); 
      Document doc = db.parse (is);      

      // Parse XSLT and Configure Transformer 
      Source xslt = new StreamSource(new StringReader(xslStr)); 
      Transformer tf = TransformerFactory.newInstance().newTransformer(xslt); 

      // Output Result to String 
      DOMSource source = new DOMSource(doc); 
      StringWriter outWriter = new StringWriter(); 
      StreamResult strresult = new StreamResult(outWriter);   
      tf.transform(source, strresult); 
      StringBuffer sb = outWriter.getBuffer(); 
      String finalstring = sb.toString(); 

      return(finalstring); 

     } catch (Exception e) { 
      System.out.println("Could not parse message as xml: " + e.getMessage()); 
     } 
      return "";  
    } 
} 
関連する問題