我的C#应用程序中有以下字符串:
string strData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
strData += "<query:querySubmission>";
strData += " <submitter>";
strData += " <entityDBID>ghjgj</entityDBID>";
strData += " <vendorID>1fghfhfh</vendorID>";
strData += " </submitter>";
strData += " <payment>";
strData += " <creditCard>";
strData += " <number>4111111111111111</number>";
strData += " <expirationDate>2016-02-01</expirationDate>";
strData += " <cardholderName>JOE SMITH</cardholderName>";
strData += " </creditCard>";
strData += " </payment>";
strData += "</query:querySubmission>";
我正在尝试将其保存在XML格式文件中并保留空格。我做了以下事情:
XmlDocument xm = new XmlDocument();
XmlTextWriter wr = new XmlTextWriter(@"C:\Users\EMWorks\Documents\text.xml",Encoding.UTF8);
wr.Formatting = Formatting.Indented;
xm.LoadXml(strData);
xm.Save(wr);
wr.Close();
我一直收到以下错误:
'query' is an undeclared prefix
我该如何解决?
答案 0 :(得分:2)
您需要声明一个由query
前缀表示的命名空间。如果您使用的是特定应用程序中的模式,则应将其记录在某处。命名空间通常声明为URI(http://something
)。
如果您只想测试文件的生成,可以使用一些任意名称空间名称,例如ns1
(稍后再更改)。您只需要向根元素添加xmlns
声明:
strData += "<query:querySubmission xmlns:query='ns1'>";
前缀/名称空间映射将应用于声明它的前缀节点以及任何带前缀的后代。
答案 1 :(得分:2)
您需要通过在文档中添加query
来声明xmlns:query="some URI"
命名空间。
您可以在此处查看一些详尽的文档:http://www.w3.org/TR/REC-xml-names/
答案 2 :(得分:0)
为了使用名称空间前缀(例如查询:),必须通过编写xmlns来声明名称空间:query ='URI'。
string strData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
strData += "<query:querySubmission xmlns:query='ns'>";
strData += " <submitter>";
strData += " <entityDBID>ghjgj</entityDBID>";
strData += " <vendorID>1fghfhfh</vendorID>";
strData += " </submitter>"
strData += " <payment>";
strData += " <creditCard>";
strData += " <number>4111111111111111</number>";
strData += " <expirationDate>2016-02-01</expirationDate>";
strData += " <cardholderName>JOE SMITH</cardholderName>";
strData += " </creditCard>";
strData += " </payment>";
strData += "</query:querySubmission>";
//the using block is used to automatically dispose resources
using (var wr= new XmlTextWriter(@"C:\test\text.xml", Encoding.UTF8))
{
wr.Formatting = Formatting.Indented;
XmlDocument xm = new XmlDocument();
xm.LoadXml(strData);
xm.Save(wr);
}