简体   繁体   中英

Dom Set element error

Im using Dom to create xml file and I'm not able to write tags attribute like below

<m:FC_TargetPath="SyndicationUpdated" m:FC_KeepInContent="false" rt:filterable="false">

when I set the attribute I succeed with the name and value but the with the m: or rt: prefix i get an exception. Any idea how I can handle it?

This is the code that im using

ent.setAttribute("m:FC_TargetPath", "SyndicationUpdated");

the exception is

 'Namespace for prefix 'm' has not been declared. 

要设置名称空间中的属性,您需要使用setAttributeNS而不是setAttribute ,并将适当的名称空间URI传递给它。

Sample program below:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Dom
{
   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 ));
   }
}

Output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root
    xmlns:m="http://www.lfinance.fr/blog-rachat-credits"
    xmlns:rt="http://www.lfinance.fr/forum-rachat-credits">
    <simple
        m:FC_KeepInContent="false"
        m:FC_TargetPath="false"
        rt:filterable="false" />
</root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM