我尝试使用domainpeople.com API,并且我需要使用XML。
目前我有一个错误说“找不到apiProtocol”我想我的Xml文档格式不正确。
发送的当前xml是:
<apiProtocol version="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNameSpaceSchemaLocation="checkrequest.xsd">
<checkRequest user="ifuzion" password="fish4gold121" reference="123456789">
<domain name="google.com" />
</checkRequest>
</apiProtocol>
显然<?xml?>
部分不会打印出来。
我的代码基本上类似于:
XDocument xDocument = new XDocument(
new XDeclaration("1.0", "UTF-8", "yes"),
new XElement("Books"));
(我删除了我的代码以获得简单的问题,但结构完全相似)。
XDocument没有打印出<?xml?>
部分的原因吗?似乎使用XmlDocument它可以工作但不能使用XDocument ...任何提示?
答案 0 :(得分:16)
答案 1 :(得分:10)
你如何保存?如果我执行以下操作,xml声明将按原样出现:
XDocument xDocument = new XDocument(
new XDeclaration("1.0", "UTF-8", "yes"),
new XElement("Books"));
xDocument.Save(@"c:\temp\file.xml");
输出如下:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Books />
但是,如果我改为传递XmlWriter实例,似乎该XmlWriter的设置会覆盖XDocument中所述的内容:
XDocument xDocument = new XDocument(
new XDeclaration("1.0", "UTF-8", "yes"),
new XElement("Books"));
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{
xDocument.Save(writer);
}
Console.WriteLine(sb.ToString());
输出如下:
<?xml version="1.0" encoding="utf-16" standalone="yes"?><Books />
请注意编码如何更改为“utf-16”并且缩进已更改。如果添加指示编码的XmlWriterSettings实例(以及您要控制的任何其他设置),则会获得更好的结果。以下代码符合您的期望:
XDocument xDocument = new XDocument(
new XDeclaration("1.0", "UTF-8", "yes"),
new XElement("Books"));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(@"c:\temp\xdocument.xml", settings))
{
xDocument.Save(writer);
}
输出:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Books />
答案 2 :(得分:1)
序列化为字符串的解决方案:
// Default encode as Utf8
Encoding outputEncoding = new UTF8Encoding(/*bom*/false);
// Try to use Xml encoding
if (xml.Declaration != null &&
xml.Declaration.Encoding.ToNonNull().ToLower() != System.Text.Encoding.UTF8.WebName)
{
outputEncoding = System.Text.Encoding.GetEncoding(xml.Declaration.Encoding);
}
using (var stream = new MemoryStream())
{
using (new XmlTextWriter(stream, outputEncoding))
{
xml.Save(stream);
}
return outputEncoding.GetString(stream.ToArray());
}
答案 3 :(得分:0)
您是否尝试保存XDocument?
xDocument.Save("books.xml");
看看这个问题how-to-print-xml-version1-0-using-xdocument
以下是文档:XDocument.Save Method