0

次のようなxmlがあります

<Students xmlns="http://AdapterTest">
<Schema name="Schema1" xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes">
    <ElementType name="Student" content="empty" model="closed">
        <AttributeType name="Student_id" dt:type="string"/>
        <AttributeType name="Student_Name" dt:type="string"/>
        <attribute type="Student_id"/>
        <attribute type="Student_Name"/>
    </ElementType>
</Schema>
<Student Student_id="123456" Student_Name="Udaya" xmlns="x-schema:#Schema1"/>
<Student Student_id="568923" Student_Name="Christie" xmlns="x-schema:#Schema1"/>
<Student Student_id="741852" Student_Name="Test Name" xmlns="x-schema:#Schema1"/>
<Student Student_id="852789" Student_Name="Sample Name" xmlns="x-schema:#Schema1"/>
</Students>

私のアプリケーションでは、次のように LINQ を使用してノードにアクセスしようとしています。

XDocument xdoc1 = XDocument.Load("Customer.xml");

        List<Student> studentList =
            (from _student in xdoc1.Element("Students").Elements("Student")
             select new Student
             {
                 firstName = _student.Attribute("Student_id").Value,
                 lastName = _student.Attribute("Student_Name").Value,


             }).ToList();

オブジェクトのインスタンスに設定されていないオブジェクト参照が返されます。ルート要素から xmlns="http://AdapterTest" を削除すると、正常に動作します。ここに欠けているもの

4

3 に答える 3

1

このような前に同様の問題がありました。あなたが言ったように、xmlから名前空間を削除すると機能します。次のようなことをしなければなりません:

XNamespace rootNs = xdoc1.Root.Name.Namespace;
XNamespace studentNS = "x-schema:#Schema1";

次に、ノードを選択するときに、次のようにセレクターの先頭に ns を追加します。

var yourStudentList = xdoc1.Element(rootNS + "Student").Elements(studentNS + "Student");

私はこれをテストしていませんが、私が抱えていた問題と似ています。

于 2012-07-19T07:53:30.747 に答える
1

名前空間を追加します。

        XNamespace ns1 = xdoc1.Root.GetDefaultNamespace();
        XNamespace ns2 = "x-schema:#Schema1";

要素を取得するときにそれらを使用します。

        List<Student> studentList =
            (from _student in xdoc1.Element(ns1 + "Students")
                                   .Elements(ns2 + "Student")
             select new Student
             {
                 firstName = _student.Attribute("Student_id").Value,
                 lastName = _student.Attribute("Student_Name").Value,
             }).ToList();

そして、4 つの要素を含むリストを取得します。

于 2012-07-19T08:00:58.377 に答える
0

LINQ の名前空間を定義する必要があります。

XDocument xdoc1 = XDocument.Load("Customer.xml");
XNamespace ns = "http://AdapterTest"; //definine namespace

    List<Student> studentList =
        (from _student in xdoc1.Element(ns + "Students").Elements("Student")
         select new Student
         {
             firstName = _student.Attribute("Student_id").Value,
             lastName = _student.Attribute("Student_Name").Value,


         }).ToList();
于 2012-07-19T08:01:00.980 に答える