2011-10-11 90 views
2

我有测试的xml文件,看起来像这样:如何忽略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

你用什么来反序列化? –

+0

您的示例XML和错误消息不一致; xsi/xsd只是名称空间别名 - 它们不会更改任何内容。你可以非常忽略这两个。然而,'xmlns ='... blah ...''非常重要。请澄清:这是否在您的XML或不?如果是,则必须提前告知XmlSerializer –

回答

4

命名空间是XML的基础(与可互换的名称空间不同)。如果人在该命名空间,你必须告诉它:

[XmlRoot(Namespace="http://tempuri.org/PaymentInformationXml.xsd")] 
public class Person {...} 
0

结帐XmlSerializerNamespaces

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类型需要与您序列化时所使用的一致。

+0

问题不在于xsi/xsd,而在于xmlns =这意味着XmlSerializerNamespaces在此处不执行任何操作, –

0

有关于XML的文章here

,我也迷迷糊糊accros这段代码:(非常有益)

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

希望这可以帮助