我有一个看起来像这样的测试xml文件:
<Person>
<ContactInfo>
...
<ContactInfo>
</Person>
当我尝试反序列化时,一切正常。 但问题是有时这个xml文件的结构是不同的 - 有时会添加xml命名空间。
<Person xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<ContactInfo>
...
<ContactInfo>
</Person>
现在当我进行序列化时,我得到IOnvalidOperationException:“XML文档中存在错误(1,2)”。内部异常消息显示<Person xmlns='http://tempuri.org/PaymentInformationXml.xsd'>
未被预期。
所以有人可以帮我这个吗?
答案 0 :(得分:4)
命名空间是XML的基础(与可互换的命名空间不同)。如果Person在该命名空间中,您必须告诉它:
[XmlRoot(Namespace="http://tempuri.org/PaymentInformationXml.xsd")]
public class Person {...}
答案 1 :(得分:0)
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsd", "http://www.w3.org/2001/XMLSchema");
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
可以直接在XmlSerializer上控制默认命名空间:
XmlSerializer xs = new XmlSerializer(typeof(Person), "http://tempuri.org/PaymentInformationXml.xsd");
...但你的问题有点不清楚问题的来源。
检查您的Person
班级[XmlType]
属性:
[XmlType(Namespace="http://tempuri.org/PaymentInformationXml.xsd")]
public class Person
{
//...
}
Person
类型的命名空间需要与序列化时使用的命名空间保持一致。
答案 2 :(得分:0)
有一篇关于xml here
的文章我也偶然发现了这段代码:(非常有帮助)
XmlDocument stripDocumentNamespace(XmlDocument oldDom)
{
// Remove all xmlns:* instances from the passed XmlDocument
// to simplify our xpath expressions.
XmlDocument newDom = new XmlDocument();
newDom.LoadXml(System.Text.RegularExpressions.Regex.Replace(
oldDom.OuterXml, @"(xmlns:?[^=]*=[""][^""]*[""])", "",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline)
);
return newDom;
}
希望这可以帮助