2016-03-21 196 views
0

我不得不解析一個xmlns:xsi =「http://www.w3.org/2001/XMLSchema-instance」命名空間丟失的XML,所以xml看起來像這樣:解析器缺少XML命名空間

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<program> 
    <scriptList> 
    <script type="StartScript"> 
    <isUserScript>false</isUserScript> 
    </script> 
    </scriptList> 
</program> 

,但應該是這樣的:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<program xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > 
    <scriptList> 
    <script xsi:type="StartScript"> 
     <isUserScript>false</isUserScript> 
    </script> 
    </scriptList> 
</program> 

類型屬性確保正確的子類如

class StartScript : script 
{...} 

解析器是從手寫的xsd通過$> xsd.exe a.xsd/classes(.Net)自動生成的。 這裏是XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
elementFormDefault="qualified" attributeFormDefault="qualified"> 

    <!-- Main element --> 
    <xs:element name="program"> 
    <xs:complexType> 
     <xs:sequence> 
     <xs:element name="scriptList"> 
      <xs:complexType> 
      <xs:sequence> 
       <xs:element name="script" type="script" maxOccurs="unbounded"/> 
      </xs:sequence> 
      </xs:complexType> 
     </xs:element> 
     </xs:sequence> 
    </xs:complexType> 
    </xs:element> 

    <xs:complexType name="script" /> 

    <xs:complexType name="StartScript"> 
    <xs:complexContent> 
     <xs:extension base="script"> 
     <xs:all> 
      <xs:element name="isUserScript" type="xs:boolean"></xs:element> 
     </xs:all> 
     </xs:extension> 
    </xs:complexContent> 
    </xs:complexType> 

一個簡單的解決方案是運行一個字符串替換:對輸入XML(「類型= \‘’到‘的xsi類型= \’」),但是這是非常難看。 有更好的解決方案嗎?

+0

你如何解析它?你在使用'XmlSerializer'還是其他的東西?還有其他類型的'script'還是隻有'StartScript'? – dbc

+0

解析在C#中很簡單: _program =(new XmlSerializer(typeof(program)))。反序列化(f)爲程序; 有很多腳本,StartScript只是一個例子 – Harald

回答

1

您可以將XML加載到一箇中間LINQ to XMLXDocument,固定在<script>元素屬性的名稱空間,然後直接反序列化到最終等級:

// Load to intermediate XDocument 
XDocument xDoc; 
using (var reader = XmlReader.Create(f)) 
    xDoc = XDocument.Load(reader); 

// Fix namespace of "type" attributes 
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
foreach (var element in xDoc.Descendants("script")) 
{ 
    var attr = element.Attribute("type"); 
    if (attr == null) 
     continue; 
    var newAttr = new XAttribute(xsi + attr.Name.LocalName, attr.Value); 
    attr.Remove(); 
    element.Add(newAttr); 
} 

// Deserialize directly to final class. 
var program = xDoc.Deserialize<program>(); 

使用擴展方法:

public static class XObjectExtensions 
{ 
    public static T Deserialize<T>(this XContainer element, XmlSerializer serializer = null) 
    { 
     if (element == null) 
      throw new ArgumentNullException(); 
     using (var reader = element.CreateReader()) 
      return (T)(serializer ?? new XmlSerializer(typeof(T))).Deserialize(reader); 
    } 
}