1

我正在使用以下 API 来创建带有命名空间的 Dom 文档,我的问题是为什么我需要将第一个参数“http://www.w3.org/2000/xmlns/”放入某种常量?当我输入 null 我得到错误。我问它,因为它太通用了,所以我为什么要放它?

rootTreeNode.setAttributeNS("http://www.w3.org/2000/xmlns/" ,"xmlns:m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");

谢谢!

4

1 回答 1

1

以下是如何处理命名空间:

public static void main( String[] args ) throws Throwable {
   DocumentBuilderFactory dbf  = DocumentBuilderFactory.newInstance();
   dbf.setNamespaceAware( true );

   DocumentBuilder db = dbf.newDocumentBuilder();
   Document doc = db.newDocument();

   Element root = doc.createElement( "root" );
   root.setAttribute( "xmlns:m" , "http://www.lfinance.fr/blog-rachat-credits" );
   root.setAttribute( "xmlns:rt", "http://www.lfinance.fr/forum-rachat-credits" );
   doc.appendChild( root );

   Element elt = doc.createElement( "simple" );
   elt.setAttribute( "m:FC_TargetPath"   , "false" );
   elt.setAttribute( "m:FC_KeepInContent", "false" );
   elt.setAttribute( "rt:filterable"     , "false" );

   root.appendChild( doc.createTextNode( "\n\t" ));
   root.appendChild( elt );
   root.appendChild( doc.createTextNode( "\n" ));
   TransformerFactory.newInstance().newTransformer().transform(
      new DOMSource( doc ),
      new StreamResult( System.out ));
}
于 2012-10-20T18:19:50.930 回答