2011-10-11 88 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; 
} 

希望這可以幫助