簡體   English   中英

解析器缺少XML名稱空間

[英]XML namespace missing for parser

我必須解析缺少xmlns:xsi =“ http://www.w3.org/2001/XMLSchema-instance”名稱空間的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>

type屬性確保正確的子類,例如

class StartScript : script
{...}

解析器是通過$> xsd.exe a.xsd / classes(.Net)從手寫的xsd自動生成的。 這是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上運行字符串替換(“ type = \\”“到” xsi:type = \\“”),但這很丑陋。 有更好的解決方案嗎?

您可以將XML加載到XML XDocument的中間LINQ中 ,修復<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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM