2008-11-20 72 views

回答

5

我認爲你需要在命名空間前綴nil =「true」以便XmlSerializer反序列化爲null。

MSDN on xsi:nil

<?xml version="1.0" encoding="UTF-8"?> 
<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="array"> 
    <entity> 
    <id xsi:type="integer">1</id> 
    <name>Foo</name> 
    <parent-id xsi:type="integer" xsi:nil="true"/> 
+0

感謝菲爾,那工作的一種享受。現在我只需要讓提供消息的人添加命名空間...... – 2008-11-21 09:11:55

+0

不用擔心SCOA :-P如果您無法在源代碼中更改XML(聽起來像您可以),您可以通過XSLT轉換添加命名空間,我認爲... – 2008-11-21 09:16:36

3

我的解決辦法是預先處理節點,修復任何「無」屬性:

public static void FixNilAttributeName(this XmlNode @this) 
{ 
    XmlAttribute nilAttribute = @this.Attributes["nil"]; 
    if (nilAttribute == null) 
    { 
     return; 
    } 

    XmlAttribute newNil = @this.OwnerDocument.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance"); 
    newNil.Value = nilAttribute.Value; 
    @this.Attributes.Remove(nilAttribute); 
    @this.Attributes.Append(newNil); 
} 

我夫婦這與子節點遞歸搜索,所以對於任何給定的XmlNode(或XmlDocument),我都可以在反序列化之前發出一個單獨的調用。如果您想保持原始的內存結構不被修改,請使用XmlNode的Clone()。

0

非常懶惰的做法。由於多種原因,它很脆弱,但是我的XML非常簡單,足以保證這種快速而髒的修復。

xmlStr = Regex.Replace(xmlStr, "nil=\"true\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\""); 
相關問題