我通常会搜索网页的最高和最低的答案,但这次我画了一个空白。我使用VS2005将代码写入POST xml到API。我有C#中的类设置,我序列化成一个XML文档。这些类如下所示:在C#中序列化XML#
[Serializable]
[XmlRoot(Namespace = "", IsNullable = false)]
public class Request
{
public RequestIdentify Identify;
public string Method;
public string Params;
}
[Serializable]
public class RequestIdentify
{
public string StoreId;
public string Password;
}
当我序列化此我得到:
<?xml version="1.0" encoding="UTF-8"?>
<Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Identify>
<StoreId>00</StoreId>
<Password>removed for security</Password>
</Identify>
<Method>ProductExport</Method>
<Params />
</Request>
但API返回一个 “没有XML派” 的错误。
如果我直接发送XML字符串中的为:
string xml = @"<Request><Identify><StoreId>00</StoreId><Password>Removed for security</Password></Identify><Method>ProductExport</Method><Params /></Request>";
有效地发送该XML(而不在“请求”标签模式的信息):
<Request>
<Identify>
<StoreId>00</StoreId>
<Password>Removed for security</Password>
</Identify>
<Method>ProductExport</Method>
<Params />
</Request>
这似乎认识XML没有问题。
所以我想我的问题是如何将我的当前类更改为序列化到XML并获得XML在第二种情况下?我假设我需要另一个“父”类来包装现有的和对这个“父母”或类似的东西使用InnerXml属性,但我不知道如何做到这一点。
对这个问题抱歉,我只用了3个月的C#,而且我是一名实习教师,不得不在工作中自学!
哦和PS我不知道为什么,但VS2005真的不想让我用私有变量设置这些类,然后使用公共等价物的getter和setter,所以我让他们写出它们现在的样子。
在此先感谢:-)
UPDATE:
与大多数事情一样也很难,如果你不知道你需要问什么或如何词它来寻找答案,而是:
一旦我知道要寻找什么,我发现我所需要的答案:
删除XML声明:
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
StringWriter stringWriter = new StringWriter();
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
serializer.Serialize(xmlWriter, request);
}
string xmlText = stringWriter.ToString();
拆卸/设置命名空间(由于上述答复,帮助找到这一个!):
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
感谢您的帮助大家谁回答或向我指出了正确的方向!是的,一旦我知道我在问什么,我确实找到要阅读的文章:-)这是我第一次在3个月的时间里自我教导,因此我认为自己做得很好...
的可能的复制[XmlSerializer的:除去不必要的xsi和xsd命名空间(http://stackoverflow.com/questions/760262/xmlserializer-remove-unnecessary-xsi-and-xsd-namespaces) – J0HN
不是解决方案,但您可以尝试通过用空字符串替换命名空间属性来操纵字符串xml。 –
请显示如何序列化您的课程。我猜你需要'XmlSerializerNamespaces _namespaces = new XmlSerializerNamespaces(new [] {XmlQualifiedName.Empty}); serializer.Serialize(writer,data,_namespaces);' – Reniuz