3

XML ファイルがあるとします。

<experiment
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="experiment.xsd">
  <something />
<experiment>

そして、あなたはxsdファイルを持っています:

...
<xs:attribute name="hello" type="xs:boolean" use="optional" default="false" />
...

属性「hello」が「something」要素のオプション属性であり、デフォルト値が「false」に設定されていると仮定しましょう。

XML LINQ の XDocument を使用する場合、属性が欠落しているため、プログラムが読み取ろうとして失敗します。

XDocument xml = XDocument.Load("file.xml");
bool b = bool.Parse(xml.Descendants("something").First().Attribute("hello").Value); // FAIL

LINQ は XML スキーマを (ルート要素 "experiment" の "xsi:noNamespaceSchemaLocation" 属性から) 自動的に読み込みますか、それとも手動で強制する必要がありますか?

オプションの属性とそのデフォルト値をLINQに強制的に読み取らせる方法は?

4

2 に答える 2

6

適切な XmlReaderSettings http://msdn.microsoft.com/en-us/library/1xe0740aLoadを使用する場合、このメソッドは XmlReader を取ります(つまり、ValidationType を schema に設定して検証を要求し、適切なValidationFlags) の場合、属性が作成され、スキーマのデフォルトが設定されると思います。

以下に短いサンプルを示します。

    XDocument doc;

    XmlReaderSettings xrs = new XmlReaderSettings();
    xrs.ValidationType = ValidationType.Schema;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;


    using (XmlReader xr = XmlReader.Create("../../XMLFile1.xml", xrs))
    {
        doc = XDocument.Load(xr);
    }
    foreach (XElement foo in doc.Root.Elements("foo"))
    {
        Console.WriteLine("bar: {0}", (bool)foo.Attribute("bar"));
    }

中身のあるサンプルファイル付き

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="XMLSchema1.xsd">
  <foo/>
  <foo bar="true"/>
  <foo bar="false"/>
</root>

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence maxOccurs="unbounded">
        <xs:element name="foo">
          <xs:complexType>
            <xs:attribute name="bar" use="optional" type="xs:boolean" default="false"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

出力は

bar: False
bar: True
bar: False
于 2012-06-28T14:18:16.297 に答える
1

このXml ライブラリXElementExtensions.cs クラスを使用するGet()と、デフォルト値を取るメソッドを使用できます。

XDocument xml = XDocument.Load("file.xml");
bool b = xml.Descendants("something").First().Get("hello", false); 

false提供するデフォルトです。

于 2012-06-28T17:17:22.060 に答える