gpt4 book ai didi

java - Dom 设置元素错误

转载 作者:行者123 更新时间:2023-11-29 09:10:10 25 4
gpt4 key购买 nike

我正在使用 Dom 创建 xml 文件,但我无法编写标签属性如下

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

当我设置属性时,我成功设置了名称和值,但使用 m:rt: 前缀时出现异常。知道我该如何处理吗?

这是我使用的代码

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

异常(exception)是

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

最佳答案

示例程序如下:

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 ));
}
}

输出:

<?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>

关于java - Dom 设置元素错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12921198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com