解析器缺少XML命名空间

时间:2016-03-21 18:28:54

标签: c# xml xsd namespaces

我必须解析XML中的xmlns:xsi =" http://www.w3.org/2001/XMLSchema-instance"缺少名称空间,因此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>

type属性确保正确的子类,例如

class StartScript : script
{...}

解析器是通过$&gt;手写的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>

一个简单的解决方案是运行字符串替换(&#34; type = \&#34;&#34;到&#34; xsi:type = \&#34;&#34;)输入XML,但这非常难看。 有更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以将XML加载到中间LINQ to XML XDocument中,修复<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);
    }
}