XmlDocument クラス

定義

XML ドキュメントを表します。 このクラスを使用すると、XML のドキュメントへの読み込み、検証、編集、追加、および配置が可能です。

public ref class XmlDocument : System::Xml::XmlNode
public class XmlDocument : System.Xml.XmlNode
type XmlDocument = class
    inherit XmlNode
Public Class XmlDocument
Inherits XmlNode
継承
XmlDocument
派生

注釈

クラスは XmlDocument 、XML ドキュメントのメモリ内表現です。 W3C XML ドキュメント オブジェクト モデル (DOM) レベル 1 コアとコア DOM レベル 2 を実装します。

DOMドキュメント オブジェクト モデルを表します。 詳細については、「 XML ドキュメント オブジェクト モデル (DOM)」を参照してください。

クラスを使用 XmlDocument して DOM に XML を読み込み、プログラムでドキュメント内の XML の読み取り、変更、および削除を行うことができます。

クラスを開いて実装方法を XmlDocument 確認する場合は、「 参照ソース」を参照してください。

タスク

ドキュメント オブジェクト モデルに XML を読み込む

コレクション内のいくつかの書籍を含むこのような XML ドキュメントから始めます。 これには、名前空間、データを表す要素、データを記述する属性など、XML ドキュメントで見つかる基本的なものが含まれています。

<?xml version="1.0" encoding="utf-8"?>  
<books xmlns="http://www.contoso.com/books">  
  <book genre="novel" ISBN="1-861001-57-8" publicationdate="1823-01-28">  
    <title>Pride And Prejudice</title>  
    <price>24.95</price>  
  </book>  
  <book genre="novel" ISBN="1-861002-30-1" publicationdate="1985-01-01">  
    <title>The Handmaid's Tale</title>  
    <price>29.95</price>  
  </book>  
  <book genre="novel" ISBN="1-861001-45-3" publicationdate="1811-01-01">  
    <title>Sense and Sensibility</title>  
    <price>19.95</price>  
  </book>  
</books>  

次に、メモリ内で操作できるように、このデータを DOM に読み込みます。 これを行う最も一般的な方法は、ローカル コンピューターまたはネットワーク上のファイルを参照することです。

この例では、ファイルから XML を読み込みます。 ファイルが存在しない場合は、XML を生成して読み込むだけです。

XmlDocument ^doc = gcnew XmlDocument();
doc->PreserveWhitespace = true;
try
{doc->Load("booksData.xml");}
catch (System::IO::FileNotFoundException ^e1)
{
    // If no book is found, generate some XML.

    doc->LoadXml("<?xml version=\"1.0\"?> \n" +
    "<books xmlns=\"http://www.contoso.com/books\"> \n" +
    "  <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
    "    <title>Pride And Prejudice</title> \n" +
    "    <price>24.95</price> \n" +
    "  </book> \n" +
    "  <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
    "    <title>The Handmaid's Tale</title> \n" +
    "    <price>29.95</price> \n" +
    "  </book> \n" +
    "</books>");
}
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
try { doc.Load("booksData.xml"); }
catch (System.IO.FileNotFoundException)
{
    doc.LoadXml("<?xml version=\"1.0\"?> \n" +
    "<books xmlns=\"http://www.contoso.com/books\"> \n" +
    "  <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
    "    <title>Pride And Prejudice</title> \n" +
    "    <price>24.95</price> \n" +
    "  </book> \n" +
    "  <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
    "    <title>The Handmaid's Tale</title> \n" +
    "    <price>29.95</price> \n" +
    "  </book> \n" +
    "</books>");
}
Dim doc As XmlDocument = New XmlDocument
doc.PreserveWhitespace = True
Try
    doc.Load("booksData.xml")
Catch ex As System.IO.FileNotFoundException
    ' If no file is found, generate some XML.
    doc.LoadXml("<?xml version=""1.0""?> " & ControlChars.NewLine & _
        "<books xmlns=""http://www.contoso.com/books""> " & ControlChars.NewLine & _
        "  <book genre=""novel"" ISBN=""1-861001-57-8"" publicationdate=""1823-01-28""> " & ControlChars.NewLine & _
        "    <title>Pride And Prejudice</title> " & ControlChars.NewLine & _
        "    <price>24.95</price> " & ControlChars.NewLine & _
        "  </book> " & ControlChars.NewLine & _
        "  <book genre=""novel"" ISBN=""1-861002-30-1"" publicationdate=""1985-01-01""> " & ControlChars.NewLine & _
        "    <title>The Handmaid's Tale</title> " & ControlChars.NewLine & _
        "    <price>29.95</price> " & ControlChars.NewLine & _
        "  </book> " & ControlChars.NewLine & _
        "</books>")
End Try

詳細情報:DOM への XML ドキュメントの読み取り

スキーマに対して検証する

次のような XML スキーマから始めます。 このスキーマでは、XML 内のデータ型と、必要な属性を定義します。

<?xml version="1.0" encoding="utf-8"?>  
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"  
  attributeFormDefault="unqualified"   
  elementFormDefault="qualified"  
  targetNamespace="http://www.contoso.com/books">   
  <xs:element name="books">  
    <xs:complexType>  
      <xs:sequence>  
        <xs:element maxOccurs="unbounded" name="book">  
          <xs:complexType>  
            <xs:sequence>  
              <xs:element name="title" type="xs:string" />  
              <xs:element name="price" type="xs:decimal" />  
            </xs:sequence>  
            <xs:attribute name="genre" type="xs:string" use="required" />  
            <xs:attribute name="ISBN" type="xs:string" use="required" />  
            <xs:attribute name="publicationdate" type="xs:date" use="required" />  
          </xs:complexType>  
        </xs:element>  
      </xs:sequence>  
    </xs:complexType>  
  </xs:element>  
</xs:schema>  

スキーマを XmlReader 使用してオブジェクトを作成し、そのオブジェクトを DOM に読み込みます。 コードがスキーマの規則に違反する方法で XML ファイルを変更しようとしたときに実行されるイベント ハンドラーを作成します。

これらのコード ブロックは、このすべてを実行するヘルパー メソッドを示しています。

//************************************************************************************
//
//  Associate the schema with XML. Then, load the XML and validate it against
//  the schema.
//
//************************************************************************************

XmlDocument ^XMLDOMProcessing::XMLHelperMethods::LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
    XmlReader ^reader;

    XmlReaderSettings ^settings = gcnew XmlReaderSettings();

    // Helper method to retrieve schema.
    XmlSchema ^schema = getSchema(generateSchema);
    
    if (schema == nullptr)
    {
        return nullptr;
    }

    settings->Schemas->Add(schema);
    settings->ValidationEventHandler +=
        gcnew System::Xml::Schema::ValidationEventHandler
        (this, &XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler);
    settings->ValidationFlags = settings->ValidationFlags | XmlSchemaValidationFlags::ReportValidationWarnings;
    settings->ValidationType = ValidationType::Schema;

    try
    {
        reader = XmlReader::Create("booksData.xml", settings);
    }
    catch (System::IO::FileNotFoundException ^e1)
    {
        if (generateXML)
        {
            String ^xml = generateXMLString();
            array<Byte> ^byteArray = Encoding::UTF8->GetBytes(xml);
            MemoryStream ^stream = gcnew MemoryStream(byteArray);
            reader = XmlReader::Create(stream, settings);
        }
        else
        {
            return nullptr;
        }

    }

    XmlDocument ^doc = gcnew XmlDocument();
    doc->PreserveWhitespace = true;
    doc->Load(reader);
    reader->Close();

    return doc;
}

//************************************************************************************
//
//  Helper method that generates an XML Schema.
//
//************************************************************************************

String ^XMLDOMProcessing::XMLHelperMethods::generateXMLSchema()
{
    String ^xmlSchema = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " + 
        "<xs:schema attributeFormDefault=\"unqualified\" " + 
        "elementFormDefault=\"qualified\" targetNamespace=\"http://www.contoso.com/books\" " + 
        "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"> " + "<xs:element name=\"books\"> " + 
        "<xs:complexType> " + "<xs:sequence> " + "<xs:element maxOccurs=\"unbounded\" name=\"book\"> " + 
        "<xs:complexType> " + "<xs:sequence> " + "<xs:element name=\"title\" type=\"xs:string\" /> " + 
        "<xs:element name=\"price\" type=\"xs:decimal\" /> " + "</xs:sequence> " + 
        "<xs:attribute name=\"genre\" type=\"xs:string\" use=\"required\" /> " + 
        "<xs:attribute name=\"publicationdate\" type=\"xs:date\" use=\"required\" /> " + 
        "<xs:attribute name=\"ISBN\" type=\"xs:string\" use=\"required\" /> " + "</xs:complexType> " + 
        "</xs:element> " + "</xs:sequence> " + "</xs:complexType> " + "</xs:element> " + "</xs:schema> ";
    
    return xmlSchema;
}

//************************************************************************************
//
//  Helper method that gets a schema
//
//************************************************************************************

XmlSchema ^XMLDOMProcessing::XMLHelperMethods::getSchema(bool generateSchema)
{
    XmlSchemaSet ^xs = gcnew XmlSchemaSet();
    XmlSchema ^schema;
    try
    {
        schema = xs->Add("http://www.contoso.com/books", "booksData.xsd");
    }
    catch (System::IO::FileNotFoundException ^e1)
    {
        if (generateSchema)
        {
            String ^xmlSchemaString = generateXMLSchema();
            array<Byte> ^byteArray = Encoding::UTF8->GetBytes(xmlSchemaString);
            MemoryStream ^stream = gcnew MemoryStream(byteArray);
            XmlReader ^reader = XmlReader::Create(stream);
            schema = xs->Add("http://www.contoso.com/books", reader);
        }
        else
        {
            return nullptr;
        }

    }
    return schema;
}
//************************************************************************************
//
//  Helper method to validate the XML against the schema.
//
//************************************************************************************
bool XMLDOMProcessing::XMLHelperMethods::validateXML(bool generateSchema, XmlDocument ^doc)
{
    if (doc->Schemas->Count == 0)
    {
        // Helper method to retrieve schema.
        XmlSchema ^schema = getSchema(generateSchema);
        doc->Schemas->Add(schema);
    }

    ValidationEventHandler^ eventHandler = gcnew System::Xml::Schema::ValidationEventHandler
        (this, &XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler);

    // Use an event handler to validate the XML node against the schema.
    doc->Validate(eventHandler);

    if (_IsValid == false)
    {
        _IsValid = true;
        return false;
    }
    else
    {
        return true;
    }

}
//************************************************************************************
//
//  Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************

void XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler(System::Object ^sender, System::Xml::Schema::ValidationEventArgs ^e)
{
    if (e->Severity == XmlSeverityType::Warning)
    {
        // do nothing.
    }
    else if (e->Severity == XmlSeverityType::Error)
    {
        // set some global variables.
        _IsValid = false;
        ValidationError = e->Message;
    }
}
//************************************************************************************
//
//  Helper method that generates an XML string.
//
//************************************************************************************
private string generateXMLString()
{
    string xml = "<?xml version=\"1.0\"?> \n" +
        "<books xmlns=\"http://www.contoso.com/books\"> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
        "    <title>Pride And Prejudice</title> \n" +
        "    <price>24.95</price> \n" +
        "  </book> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
        "    <title>The Handmaid's Tale</title> \n" +
        "    <price>29.95</price> \n" +
        "  </book> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861001-45-3\" publicationdate=\"1811-01-01\"> \n" +
        "    <title>Sense and Sensibility</title> \n" +
        "    <price>19.95</price> \n" +
        "  </book> \n" +
        "</books>";
    return xml;
}

//************************************************************************************
//
//  Associate the schema with XML. Then, load the XML and validate it against
//  the schema.
//
//************************************************************************************
public XmlDocument LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
    XmlReader reader = null;
    XmlReaderSettings settings = new XmlReaderSettings();
    // Helper method to retrieve schema.
    XmlSchema schema = getSchema(generateSchema);

    settings.Schemas.Add(schema);
    settings.ValidationEventHandler += ValidationCallback;
    settings.ValidationFlags =
        settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationType = ValidationType.Schema;
    if (!generateXML)
    {
        try
        {
            reader = XmlReader.Create("booksData.xml", settings);
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine(
                $"XML file not found so generating: {ex.Message}");
            generateXML = true;
        }
    }

    if (generateXML)
    {
        string xml = generateXMLString();
        StringReader stringReader = new StringReader(xml);

        reader = XmlReader.Create(stringReader, settings);
    }

    XmlDocument doc = new XmlDocument();

    doc.PreserveWhitespace = true;
    doc.Load(reader);
    reader.Close();

    return doc;
}

//************************************************************************************
//
//  Helper method that generates an XML Schema.
//
//************************************************************************************
private string generateXMLSchema()
{
    string xmlSchema =
        "<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
        "<xs:schema attributeFormDefault=\"unqualified\" " +
        "elementFormDefault=\"qualified\" targetNamespace=\"http://www.contoso.com/books\" " +
        "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"> " +
        "<xs:element name=\"books\"> " +
        "<xs:complexType> " +
        "<xs:sequence> " +
        "<xs:element maxOccurs=\"unbounded\" name=\"book\"> " +
        "<xs:complexType> " +
        "<xs:sequence> " +
        "<xs:element name=\"title\" type=\"xs:string\" /> " +
        "<xs:element name=\"price\" type=\"xs:decimal\" /> " +
        "</xs:sequence> " +
        "<xs:attribute name=\"genre\" type=\"xs:string\" use=\"required\" /> " +
        "<xs:attribute name=\"publicationdate\" type=\"xs:date\" use=\"required\" /> " +
        "<xs:attribute name=\"ISBN\" type=\"xs:string\" use=\"required\" /> " +
        "</xs:complexType> " +
        "</xs:element> " +
        "</xs:sequence> " +
        "</xs:complexType> " +
        "</xs:element> " +
        "</xs:schema> ";
    return xmlSchema;
}

//************************************************************************************
//
//  Helper method that gets a schema
//
//************************************************************************************
private XmlSchema getSchema(bool generateSchema)
{
    XmlSchemaSet xs = new XmlSchemaSet();
    XmlSchema schema = null;

    if (!generateSchema)
    {
        try
        {
            schema = xs.Add("http://www.contoso.com/books", "booksData.xsd");
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine(
                $"XSD file not found so generating: {ex.Message}");
            generateSchema = true;
        }
    }

    if (generateSchema)
    {
        string xmlSchemaString = generateXMLSchema();
        StringReader stringReader = new StringReader(xmlSchemaString);
        XmlReader reader = XmlReader.Create(stringReader);

        schema = xs.Add("http://www.contoso.com/books", reader);
    }

    return schema;
}

//************************************************************************************
//
//  Helper method to validate the XML against the schema.
//
//************************************************************************************
private void validateXML(bool generateSchema, XmlDocument doc)
{
    if (doc.Schemas.Count == 0)
    {
        // Helper method to retrieve schema.
        XmlSchema schema = getSchema(generateSchema);
        doc.Schemas.Add(schema);
    }

    // Use a callback to validate the XML node against the schema.
    doc.Validate(ValidationCallback);
}

//************************************************************************************
//
//  Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************
void ValidationCallback(object sender,
    System.Xml.Schema.ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
    {
        Console.WriteLine
            ("The following validation warning occurred: " + e.Message);
    }
    else if (e.Severity == XmlSeverityType.Error)
    {
        Console.WriteLine
            ("The following critical validation errors occurred: " + e.Message);
    }
}
'************************************************************************************
'
'  Associate the schema with XML. Then, load the XML and validate it against
'  the schema.
'
'************************************************************************************
Public Function LoadDocumentWithSchemaValidation(ByVal generateXML As Boolean, ByVal generateSchema As Boolean) As XmlDocument
    Dim reader As XmlReader
    Dim settings As XmlReaderSettings = New XmlReaderSettings
    ' Helper method to retrieve schema.
    Dim schema As XmlSchema = getSchema(generateSchema)
    If (schema Is Nothing) Then
        Return Nothing
    End If
    settings.Schemas.Add(schema)
    AddHandler settings.ValidationEventHandler, AddressOf settings_ValidationEventHandler
    settings.ValidationFlags = (settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings)
    settings.ValidationType = ValidationType.Schema
    Try
        reader = XmlReader.Create("booksData.xml", settings)
    Catch ex As System.IO.FileNotFoundException
        If generateXML Then
            Dim xml As String = generateXMLString()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xml)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            reader = XmlReader.Create(stream, settings)
        Else
            Return Nothing
        End If
    End Try
    Dim doc As XmlDocument = New XmlDocument
    doc.PreserveWhitespace = True
    doc.Load(reader)
    reader.Close()
    Return doc
End Function

'************************************************************************************
'
'  Helper method that generates an XML Schema.
'
'************************************************************************************
Private Function generateXMLSchema() As String

    Dim generatedXmlSchema As String = "<?xml version=""1.0"" encoding=""utf-8""?> " & _
            "<xs:schema attributeFormDefault=""unqualified"" " & _
            "elementFormDefault=""qualified"" targetNamespace=""http://www.contoso.com/books"" " & _
            "xmlns:xs=""http://www.w3.org/2001/XMLSchema""> " & _
            "<xs:element name=""books""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element maxOccurs=""unbounded"" name=""book""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element name=""title"" type=""xs:string"" /> " & _
            "<xs:element name=""price"" type=""xs:decimal"" /> " & _
            "</xs:sequence> " & _
            "<xs:attribute name=""genre"" type=""xs:string"" use=""required"" /> " & _
            "<xs:attribute name=""publicationdate"" type=""xs:date"" use=""required"" /> " & _
            "<xs:attribute name=""ISBN"" type=""xs:string"" use=""required"" /> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:sequence> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:schema> "


    Return generatedXmlSchema

End Function

'************************************************************************************
'
'  Helper method that gets a schema
'
'************************************************************************************
Private Function getSchema(ByVal generateSchema As Boolean) As XmlSchema
    Dim xs As XmlSchemaSet = New XmlSchemaSet
    Dim schema As XmlSchema
    Try
        schema = xs.Add("http://www.contoso.com/books", "booksData.xsd")
    Catch ex As System.IO.FileNotFoundException
        If generateSchema Then
            Dim xmlSchemaString As String = generateXMLSchema()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xmlSchemaString)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            Dim reader As XmlReader = XmlReader.Create(stream)
            schema = xs.Add("http://www.contoso.com/books", reader)
        Else
            Return Nothing
        End If
    End Try
    Return schema
End Function

'************************************************************************************
'
'  Helper method to validate the XML against the schema.
'
'************************************************************************************
Private Sub validateXML(ByVal generateSchema As Boolean, ByVal doc As XmlDocument)
    If (doc.Schemas.Count = 0) Then
        ' Helper method to retrieve schema.
        Dim schema As XmlSchema = getSchema(generateSchema)
        doc.Schemas.Add(schema)
    End If
    ' Use an event handler to validate the XML node against the schema.
    doc.Validate(AddressOf settings_ValidationEventHandler)
End Sub

'************************************************************************************
'
'  Event handler that is raised when XML doesn't validate against the schema.
'
'************************************************************************************
Private Sub settings_ValidationEventHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs)
    If (e.Severity = XmlSeverityType.Warning) Then
        System.Windows.Forms.MessageBox.Show(("The following validation warning occurred: " & e.Message))
    ElseIf (e.Severity = XmlSeverityType.Error) Then
        System.Windows.Forms.MessageBox.Show(("The following critical validation errors occurred: " & e.Message))
        Dim objectType As Type = sender.GetType
    End If
End Sub

詳細情報:DOM での XML ドキュメントの検証

プロパティを使用して、XML ドキュメント内を移動できます。 しかし、それらを使用する前に、いくつかの用語を簡単に確認しましょう。 ドキュメントはノードで構成されています。 各ノードは、その真上に単一 の親 ノードを持ちます。 最上位ノードであるため、親ノードを持たないノードはドキュメント ルートだけです。 ほとんどのノードには ノードを含めることができます。これは、その直下のノードです。 同じレベルのノードは 兄弟です

次の例では、ルート ノードを取得し、ルート ノードの最初の子ノードにジャンプし、その子ノードのいずれかにアクセスし、親ノードに戻り、兄弟ノード間を移動する方法を示します。

ルート ノードから開始する

次の使用例は、ルート ノードを取得し、そのノードを使用してドキュメントの内容をコンソールに出力します。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<?xml version='1.0' ?><book genre='novel' ISBN='1-861001-57-5'><title>Pride And Prejudice</title></book>" );
   
   //Display the document element.
   Console::WriteLine( doc->DocumentElement->OuterXml );
}

using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<?xml version='1.0' ?>" +
                "<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>");

    //Display the document element.
    Console.WriteLine(doc.DocumentElement.OuterXml);
 }
}
Option Strict
Option Explicit

Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.LoadXml("<?xml version='1.0' ?>" & _
                    "<book genre='novel' ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "</book>")
        
        'Display the document element.
        Console.WriteLine(doc.DocumentElement.OuterXml)
    End Sub
End Class

子ノードを取得する

次の使用例は、ルート ノードの最初の子ノードにジャンプし、存在する場合はそのノードの子ノードを反復処理します。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<book ISBN='1-861001-57-5'>"
   "<title>Pride And Prejudice</title>"
   "<price>19.95</price>"
   "</book>" );
   XmlNode^ root = doc->FirstChild;
   
   //Display the contents of the child nodes.
   if ( root->HasChildNodes )
   {
      for ( int i = 0; i < root->ChildNodes->Count; i++ )
      {
         Console::WriteLine( root->ChildNodes[ i ]->InnerText );
      }
   }
}
using System;
using System.Xml;

public class Sample2
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "<price>19.95</price>" +
                    "</book>");

        XmlNode root = doc.FirstChild;

        //Display the contents of the child nodes.
        if (root.HasChildNodes)
        {
            for (int i = 0; i < root.ChildNodes.Count; i++)
            {
                Console.WriteLine(root.ChildNodes[i].InnerText);
            }
        }
    }
}
Option Strict
Option Explicit

Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        
        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "<price>19.95</price>" & _
                    "</book>")
        
        Dim root As XmlNode = doc.FirstChild
        
        'Display the contents of the child nodes.
        If root.HasChildNodes Then
            Dim i As Integer
            For i = 0 To root.ChildNodes.Count - 1
                Console.WriteLine(root.ChildNodes(i).InnerText)
            Next i
        End If
    End Sub
End Class

親ノードに戻る

ParentNode プロパティを使用します。

最後の子ノードを参照する

次の使用例は、書籍の価格をコンソールに書き込みます。 価格ノードは、書籍ノードの最後の子です。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<book ISBN='1-861001-57-5'>"
   "<title>Pride And Prejudice</title>"
   "<price>19.95</price>"
   "</book>" );
   XmlNode^ root = doc->FirstChild;
   Console::WriteLine( "Display the price element..." );
   Console::WriteLine( root->LastChild->OuterXml );
}

using System;
using System.Xml;

public class Sample3
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "<price>19.95</price>" +
                    "</book>");

        XmlNode root = doc.FirstChild;

        Console.WriteLine("Display the price element...");
        Console.WriteLine(root.LastChild.OuterXml);
    }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        
        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "<price>19.95</price>" & _
                    "</book>")
        
        Dim root As XmlNode = doc.FirstChild
        
        Console.WriteLine("Display the price element...")
        Console.WriteLine(root.LastChild.OuterXml)
    End Sub
End Class

兄弟間で前方に移動する

次の使用例は、書籍から書籍へと進みます。 ブック ノードは互いに兄弟です。

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "books.xml" );
   XmlNode^ currNode = doc->DocumentElement->FirstChild;
   Console::WriteLine( "First book..." );
   Console::WriteLine( currNode->OuterXml );
   XmlNode^ nextNode = currNode->NextSibling;
   Console::WriteLine( "\r\nSecond book..." );
   Console::WriteLine( nextNode->OuterXml );
}

using System;
using System.Xml;

public class Sample4
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("books.xml");

        XmlNode currNode = doc.DocumentElement.FirstChild;
        Console.WriteLine("First book...");
        Console.WriteLine(currNode.OuterXml);

        XmlNode nextNode = currNode.NextSibling;
        Console.WriteLine("\r\nSecond book...");
        Console.WriteLine(nextNode.OuterXml);
    }
}
Imports System.Xml
 
public class Sample 

  public shared sub Main() 

      Dim doc as XmlDocument = new XmlDocument()
      doc.Load("books.xml")

      Dim currNode as XmlNode = doc.DocumentElement.FirstChild
      Console.WriteLine("First book...")
      Console.WriteLine(currNode.OuterXml)

      Dim nextNode as XmlNode = currNode.NextSibling
      Console.WriteLine(ControlChars.LF + "Second book...")
      Console.WriteLine(nextNode.OuterXml) 

  end sub
end class

兄弟間で後方に移動する

次の使用例は、書籍から書籍に後方に移動します。

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "books.xml" );
   XmlNode^ lastNode = doc->DocumentElement->LastChild;
   Console::WriteLine( "Last book..." );
   Console::WriteLine( lastNode->OuterXml );
   XmlNode^ prevNode = lastNode->PreviousSibling;
   Console::WriteLine( "\r\nPrevious book..." );
   Console::WriteLine( prevNode->OuterXml );
}

using System;
using System.Xml;

public class Sample {

  public static void Main() {

      XmlDocument doc = new XmlDocument();
      doc.Load("books.xml");

      XmlNode lastNode = doc.DocumentElement.LastChild;
      Console.WriteLine("Last book...");
      Console.WriteLine(lastNode.OuterXml);

      XmlNode prevNode = lastNode.PreviousSibling;
      Console.WriteLine("\r\nPrevious book...");
      Console.WriteLine(prevNode.OuterXml);
  }
}
Imports System.Xml

public class Sample 

  public shared sub Main() 

      Dim doc as XmlDocument = new XmlDocument()
      doc.Load("books.xml")

      Dim lastNode as XmlNode = doc.DocumentElement.LastChild
      Console.WriteLine("Last book...")
      Console.WriteLine(lastNode.OuterXml)

      Dim prevNode as XmlNode = lastNode.PreviousSibling
      Console.WriteLine(ControlChars.LF + "Previous book...")
      Console.WriteLine(prevNode.OuterXml)  
  end sub
end class

ノードの検索

1 つ以上のデータ ノードを検索する最も一般的な方法は、XPath クエリ文字列を使用することですが、必要のないメソッドもあります。

1 つのノードを取得する

次の使用例は、ISBN 番号を使用して書籍を検索します。

XmlNode ^XMLDOMProcessing::XMLHelperMethods::GetBook(String ^uniqueAttribute, XmlDocument ^doc)
{
    XmlNamespaceManager ^nsmgr = gcnew XmlNamespaceManager(doc->NameTable);
    nsmgr->AddNamespace("bk", "http://www.contoso.com/books");
    String ^xPathString = "//bk:books/bk:book[@ISBN='" + uniqueAttribute + "']";
    XmlNode ^xmlNode = doc->DocumentElement->SelectSingleNode(xPathString, nsmgr);
    return xmlNode;
}
public XmlNode GetBook(string uniqueAttribute, XmlDocument doc)
{
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("bk", "http://www.contoso.com/books");
    string xPathString = "//bk:books/bk:book[@ISBN='" + uniqueAttribute + "']";
    XmlNode xmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr);
   return xmlNode;
}
Public Function GetBook(ByVal uniqueAttribute As String, ByVal doc As XmlDocument) As XmlNode
    Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
    nsmgr.AddNamespace("bk", "http://www.contoso.com/books")
    Dim xPathString As String = ("//bk:books/bk:book[@ISBN='" _
                & (uniqueAttribute & "']"))
    Dim xmlNode As XmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr)
    Return xmlNode
End Function

この例で使用される文字列は Xpath クエリです。 その他の例については、 XPath の例を参照してください。

を使用 GetElementById してノードを取得することもできます。 この方法を使用するには、XML ファイルのドキュメント型定義宣言で ID を定義する必要があります。

ノードを取得すると、属性または子ノードの値が取得されます。 この例では、ブック ノードでこれを行います。

void XMLDOMProcessing::XMLHelperMethods::GetBookInformation
(String ^%title, String ^%ISBN, String ^%publicationDate, String ^%price, String ^%genre, XmlNode ^book)
{
    XmlElement ^bookElement = safe_cast<XmlElement^>(book);

    // Get the attributes of a book.        
    XmlAttribute ^attr = bookElement->GetAttributeNode("ISBN");
    ISBN = attr->InnerXml;

    attr = bookElement->GetAttributeNode("genre");
    genre = attr->InnerXml;

    attr = bookElement->GetAttributeNode("publicationdate");
    publicationDate = attr->InnerXml;

    // Get the values of child elements of a book.
    title = bookElement["title"]->InnerText;
    price = bookElement["price"]->InnerText;
}
public void GetBookInformation(ref string title, ref string ISBN, ref string publicationDate,
    ref string price, ref string genre, XmlNode book)
{
    XmlElement bookElement = (XmlElement)book;

    // Get the attributes of a book.
    XmlAttribute attr = bookElement.GetAttributeNode("ISBN");
    ISBN = attr.InnerXml;

    attr = bookElement.GetAttributeNode("genre");
    genre = attr.InnerXml;

    attr = bookElement.GetAttributeNode("publicationdate");
    publicationDate = attr.InnerXml;

    // Get the values of child elements of a book.
    title = bookElement["title"].InnerText;
    price = bookElement["price"].InnerText;
}
Public Sub GetBookInformation(ByRef title As String, ByRef ISBN As String, ByRef publicationDate As String, ByRef price As String, ByRef genre As String, ByVal book As XmlNode)
    Dim bookElement As XmlElement = CType(book, XmlElement)
    ' Get the attributes of a book.        
    Dim attr As XmlAttribute = bookElement.GetAttributeNode("ISBN")
    ISBN = attr.InnerXml
    attr = bookElement.GetAttributeNode("genre")
    genre = attr.InnerXml
    attr = bookElement.GetAttributeNode("publicationdate")
    publicationDate = attr.InnerXml
    ' Get the values of child elements of a book.
    title = bookElement("title").InnerText
    price = bookElement("price").InnerText
End Sub

ノードのコレクションを取得する

次の使用例は、著者の姓が Austen であるすべての書籍を選択し、それらの書籍の価格を変更します。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "booksort.xml" );
   XmlNodeList^ nodeList;
   XmlNode^ root = doc->DocumentElement;
   nodeList = root->SelectNodes( "descendant::book[author/last-name='Austen']" );
   
   //Change the price on the books.
   System::Collections::IEnumerator^ myEnum = nodeList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      XmlNode^ book = safe_cast<XmlNode^>(myEnum->Current);
      book->LastChild->InnerText = "15.95";
   }

   Console::WriteLine( "Display the modified XML document...." );
   doc->Save( Console::Out );
}

using System;
using System.Xml;

public class Sample6
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("booksort.xml");

        XmlNodeList nodeList;
        XmlNode root = doc.DocumentElement;

        nodeList = root.SelectNodes("descendant::book[author/last-name='Austen']");

        //Change the price on the books.
        foreach (XmlNode book in nodeList)
        {
            book.LastChild.InnerText = "15.95";
        }

        Console.WriteLine("Display the modified XML document....");
        doc.Save(Console.Out);
    }
}
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

    'Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksort.xml")
           
    Dim book as XmlNode
    Dim nodeList as XmlNodeList 
    Dim root as XmlNode = doc.DocumentElement

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']")
 
    'Change the price on the books.
    for each book in nodeList      
      book.LastChild.InnerText="15.95"
    next 

    Console.WriteLine("Display the modified XML document....")
    doc.Save(Console.Out)
    
  end sub
end class

ノードの名前を使用して、ノードのコレクションを取得することもできます。 たとえば、この例では、すべての書籍タイトルのコレクションを取得します。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "books.xml" );
   
   //Display all the book titles.
   XmlNodeList^ elemList = doc->GetElementsByTagName( "title" );
   for ( int i = 0; i < elemList->Count; i++ )
   {
      Console::WriteLine( elemList[ i ]->InnerXml );
   }
}
using System;
using System.Xml;

public class Sample1
{
    public static void Main()
    {
        //Create the XmlDocument.
        XmlDocument doc = new XmlDocument();
        doc.Load("books.xml");

        //Display all the book titles.
        XmlNodeList elemList = doc.GetElementsByTagName("title");
        for (int i = 0; i < elemList.Count; i++)
        {
            Console.WriteLine(elemList[i].InnerXml);
        }
    }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.Load("books.xml")
        
        'Display all the book titles.
        Dim elemList As XmlNodeList = doc.GetElementsByTagName("title")
        Dim i As Integer
        For i = 0 To elemList.Count - 1
            Console.WriteLine(elemList(i).InnerXml)
        Next i
    End Sub
End Class

詳細情報:XPath ナビゲーションを使用してノードを選択する

ノードの編集

次の使用例は、ブック ノードとその属性を編集します。

bool XMLDOMProcessing::XMLHelperMethods::editBook(String ^title, String ^ISBN, String ^publicationDate, String ^genre, String ^price, XmlNode ^book, bool validateNode, bool generateSchema)
{

    XmlElement ^bookElement = safe_cast<XmlElement^>(book);

    // Get the attributes of a book.        
    bookElement->SetAttribute("ISBN", ISBN);
    bookElement->SetAttribute("genre", genre);
    bookElement->SetAttribute("publicationdate", publicationDate);

    // Get the values of child elements of a book.
    bookElement["title"]->InnerText = title;
    bookElement["price"]->InnerText = price;

    if (validateNode)
    {
        if (validateXML(generateSchema, bookElement->OwnerDocument))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    return true;
}
public void editBook(string title, string ISBN, string publicationDate,
    string genre, string price, XmlNode book, bool validateNode, bool generateSchema)
{

    XmlElement bookElement = (XmlElement)book;

    // Get the attributes of a book.
    bookElement.SetAttribute("ISBN", ISBN);
    bookElement.SetAttribute("genre", genre);
    bookElement.SetAttribute("publicationdate", publicationDate);

    // Get the values of child elements of a book.
    bookElement["title"].InnerText = title;
    bookElement["price"].InnerText = price;

    if (validateNode)
    {
        validateXML(generateSchema, bookElement.OwnerDocument);
    }
}
Public Sub editBook(ByVal title As String, ByVal ISBN As String,
                    ByVal publicationDate As String, ByVal genre As String,
                    ByVal price As String, ByVal book As XmlNode, ByVal validateNode As Boolean,
                    ByVal generateSchema As Boolean)

    Dim bookElement As XmlElement = CType(book, XmlElement)

    ' Get the attributes of a book.        
    bookElement.SetAttribute("ISBN", ISBN)
    bookElement.SetAttribute("genre", genre)
    bookElement.SetAttribute("publicationdate", publicationDate)

    ' Get the values of child elements of a book.
    bookElement("title").InnerText = title
    bookElement("price").InnerText = price
    If validateNode Then
        validateXML(generateSchema, bookElement.OwnerDocument)
    End If

End Sub

詳細情報:XML ドキュメント内のノード、コンテンツ、および値の変更

ノードの追加

ノードを追加するには、 メソッドまたは メソッドをCreateNode使用CreateElementします。

書籍などのデータ ノードを追加するには、 メソッドを使用します CreateElement

コメント、空白ノード、CDATA ノードなどの他の種類のノードの場合は、 メソッドを使用します CreateNode

次の使用例は、ブック ノードを作成し、そのノードに属性を追加してから、そのノードをドキュメントに追加します。

XmlElement ^XMLDOMProcessing::XMLHelperMethods::AddNewBook(String ^genre, String ^ISBN, String ^misc, String ^title, String ^price, XmlDocument ^doc)
{
    // Create a new book element.
    XmlElement ^bookElement = doc->CreateElement("book", "http://www.contoso.com/books");

    // Create attributes for book and append them to the book element.
    XmlAttribute ^attribute = doc->CreateAttribute("genre");
    attribute->Value = genre;
    bookElement->Attributes->Append(attribute);

    attribute = doc->CreateAttribute("ISBN");
    attribute->Value = ISBN;
    bookElement->Attributes->Append(attribute);

    attribute = doc->CreateAttribute("publicationdate");
    attribute->Value = misc;
    bookElement->Attributes->Append(attribute);

    // Create and append a child element for the title of the book.
    XmlElement ^titleElement = doc->CreateElement("title");
    titleElement->InnerText = title;
    bookElement->AppendChild(titleElement);

    // Introduce a newline character so that XML is nicely formatted.
    bookElement->InnerXml = bookElement->InnerXml->Replace(titleElement->OuterXml, "\n    " + titleElement->OuterXml + " \n    ");

    // Create and append a child element for the price of the book.
    XmlElement ^priceElement = doc->CreateElement("price");
    priceElement->InnerText = price;
    bookElement->AppendChild(priceElement);

    // Introduce a newline character so that XML is nicely formatted.
    bookElement->InnerXml = bookElement->InnerXml->Replace(priceElement->OuterXml, priceElement->OuterXml + "   \n  ");

    return bookElement;

}
public XmlElement AddNewBook(string genre, string ISBN, string misc,
    string title, string price, XmlDocument doc)
{
    // Create a new book element.
    XmlElement bookElement = doc.CreateElement("book", "http://www.contoso.com/books");

    // Create attributes for book and append them to the book element.
    XmlAttribute attribute = doc.CreateAttribute("genre");
    attribute.Value = genre;
    bookElement.Attributes.Append(attribute);

    attribute = doc.CreateAttribute("ISBN");
    attribute.Value = ISBN;
    bookElement.Attributes.Append(attribute);

    attribute = doc.CreateAttribute("publicationdate");
    attribute.Value = misc;
    bookElement.Attributes.Append(attribute);

    // Create and append a child element for the title of the book.
    XmlElement titleElement = doc.CreateElement("title");
    titleElement.InnerText = title;
    bookElement.AppendChild(titleElement);

    // Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml =
        bookElement.InnerXml.Replace(titleElement.OuterXml,
        "\n    " + titleElement.OuterXml + " \n    ");

    // Create and append a child element for the price of the book.
    XmlElement priceElement = doc.CreateElement("price");
    priceElement.InnerText= price;
    bookElement.AppendChild(priceElement);

    // Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml =
        bookElement.InnerXml.Replace(priceElement.OuterXml, priceElement.OuterXml + "   \n  ");

    return bookElement;
}
Public Function AddNewBook(ByVal genre As String, ByVal ISBN As String, ByVal misc As String, ByVal title As String, ByVal price As String, ByVal doc As XmlDocument) As XmlElement
    ' Create a new book element.
    Dim bookElement As XmlElement = doc.CreateElement("book", "http://www.contoso.com/books")

    ' Create attributes for book and append them to the book element.
    Dim attribute As XmlAttribute = doc.CreateAttribute("genre")
    attribute.Value = genre
    bookElement.Attributes.Append(attribute)

    attribute = doc.CreateAttribute("ISBN")
    attribute.Value = ISBN
    bookElement.Attributes.Append(attribute)

    attribute = doc.CreateAttribute("publicationdate")
    attribute.Value = misc
    bookElement.Attributes.Append(attribute)

    ' Create and append a child element for the title of the book.
    Dim titleElement As XmlElement = doc.CreateElement("title")
    titleElement.InnerText = title
    bookElement.AppendChild(titleElement)

    ' Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = bookElement.InnerXml.Replace(titleElement.OuterXml, _
                           "\n   " & titleElement.OuterXml & " " & ControlChars.NewLine + "    ")
    ' Create and append a child element for the price of the book.
    Dim priceElement As XmlElement = doc.CreateElement("price")
    priceElement.InnerText = price
    bookElement.AppendChild(priceElement)

    ' Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = bookElement.InnerXml.Replace(priceElement.OuterXml,
                                                        (priceElement.OuterXml & "   " & ControlChars.NewLine & "  "))
    Return bookElement
End Function

詳細情報:XML ドキュメントへのノードの挿入

ノードの削除

ノードを削除するには、 メソッドを使用します RemoveChild

次の使用例は、ドキュメントからブックを削除し、ブック ノードの直前に表示される空白文字を削除します。

void XMLDOMProcessing::XMLHelperMethods::deleteBook(XmlNode ^book)
{
    XmlNode ^prevNode = book->PreviousSibling;

    book->OwnerDocument->DocumentElement->RemoveChild(book);


    if (prevNode->NodeType == XmlNodeType::Whitespace || prevNode->NodeType == XmlNodeType::SignificantWhitespace)
    {
        prevNode->OwnerDocument->DocumentElement->RemoveChild(prevNode);
    }
}
public void deleteBook(XmlNode book)
{
    XmlNode prevNode = book.PreviousSibling;

    book.OwnerDocument.DocumentElement.RemoveChild(book);

    if (prevNode.NodeType == XmlNodeType.Whitespace ||
        prevNode.NodeType == XmlNodeType.SignificantWhitespace)
    {
        prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode);
    }
}
Public Sub deleteBook(ByVal book As XmlNode)

    Dim prevNode As XmlNode = book.PreviousSibling
    book.OwnerDocument.DocumentElement.RemoveChild(book)

    If ((prevNode.NodeType = XmlNodeType.Whitespace) _
                OrElse (prevNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
        prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode)

    End If
End Sub

詳細情報:XML ドキュメントからのノード、コンテンツ、値の削除

ノードの配置

メソッドと InsertAfter メソッドを使用して、ドキュメント内のノードを表示する場所をInsertBefore選択できます。

この例では、2 つのヘルパー メソッドを示します。 そのうちの 1 つは、リスト内のノードを上位に移動します。 もう 1 つはノードを下に移動します。

これらのメソッドは、ユーザーが書籍の一覧で書籍を上下に移動できるようにするアプリケーションで使用できます。 ユーザーが書籍を選択し、上下のボタンを押すと、コードでこのようなメソッドを呼び出して、対応する書籍ノードを他の書籍ノードの前後に配置できます。

//************************************************************************************
//
//  Summary: Move elements up in the XML.
//  
//
//************************************************************************************
void XMLDOMProcessing::XMLHelperMethods::MoveElementUp(XmlNode ^book)
{
    XmlNode ^previousNode = book->PreviousSibling;
    while (previousNode != nullptr && (previousNode->NodeType != XmlNodeType::Element))
    {
        previousNode = previousNode->PreviousSibling;
    }
    if (previousNode != nullptr)
    {
        XmlNode ^newLineNode = book->NextSibling;
        book->OwnerDocument->DocumentElement->RemoveChild(book);
        if (newLineNode->NodeType == XmlNodeType::Whitespace || newLineNode->NodeType == XmlNodeType::SignificantWhitespace)
        {
            newLineNode->OwnerDocument->DocumentElement->RemoveChild(newLineNode);
        }
        InsertBookElement(safe_cast<XmlElement^>(book), Constants::positionAbove, previousNode, false, false);
    }
}

//************************************************************************************
//
//  Summary: Move elements down in the XML.
//  
//
//************************************************************************************
void XMLDOMProcessing::XMLHelperMethods::MoveElementDown(XmlNode ^book)
{
    // Walk backwards until we find an element - ignore text nodes
    XmlNode ^NextNode = book->NextSibling;
    while (NextNode != nullptr && (NextNode->NodeType != XmlNodeType::Element))
    {
        NextNode = NextNode->NextSibling;
    }
    if (NextNode != nullptr)
    {
        XmlNode ^newLineNode = book->PreviousSibling;
        book->OwnerDocument->DocumentElement->RemoveChild(book);
        if (newLineNode->NodeType == XmlNodeType::Whitespace || newLineNode->NodeType == XmlNodeType::SignificantWhitespace)
        {
            newLineNode->OwnerDocument->DocumentElement->RemoveChild(newLineNode);
        }

        InsertBookElement(safe_cast<XmlElement^>(book), Constants::positionBelow, NextNode, false, false);
    }

}
//************************************************************************************
//
//  Summary: Move elements up in the XML.
//
//
//************************************************************************************

public void MoveElementUp(XmlNode book)
{
    XmlNode previousNode = book.PreviousSibling;
    while (previousNode != null && (previousNode.NodeType != XmlNodeType.Element))
    {
        previousNode = previousNode.PreviousSibling;
    }
    if (previousNode != null)
    {
        XmlNode newLineNode = book.NextSibling;
        book.OwnerDocument.DocumentElement.RemoveChild(book);
        if (newLineNode.NodeType == XmlNodeType.Whitespace |
            newLineNode.NodeType == XmlNodeType.SignificantWhitespace)
        {
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode);
        }
        InsertBookElement((XmlElement)book, Constants.positionAbove,
            previousNode, false, false);
    }
}

//************************************************************************************
//
//  Summary: Move elements down in the XML.
//
//
//************************************************************************************
public void MoveElementDown(XmlNode book)
{
    // Walk backwards until we find an element - ignore text nodes
    XmlNode NextNode = book.NextSibling;
    while (NextNode != null && (NextNode.NodeType != XmlNodeType.Element))
    {
        NextNode = NextNode.NextSibling;
    }
    if (NextNode != null)
    {
        XmlNode newLineNode = book.PreviousSibling;
        book.OwnerDocument.DocumentElement.RemoveChild(book);
        if (newLineNode.NodeType == XmlNodeType.Whitespace |
            newLineNode.NodeType == XmlNodeType.SignificantWhitespace)
        {
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode);
        }

        InsertBookElement((XmlElement)book, Constants.positionBelow,
            NextNode, false, false);
    }
}
'************************************************************************************
'
'  Summary: Move elements up in the XML.
'  
'
'************************************************************************************
Public Sub MoveElementUp(ByVal book As XmlNode)
    Dim previousNode As XmlNode = book.PreviousSibling

    While ((Not (previousNode) Is Nothing) _
                AndAlso (previousNode.NodeType <> XmlNodeType.Element))
        previousNode = previousNode.PreviousSibling

    End While
    If (Not (previousNode) Is Nothing) Then
        Dim newLineNode As XmlNode = book.NextSibling
        book.OwnerDocument.DocumentElement.RemoveChild(book)

        If ((newLineNode.NodeType = XmlNodeType.Whitespace) _
                    Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode)
        End If

        InsertBookElement(CType(book, XmlElement), Constants.positionAbove,
                          previousNode, False, False)
    End If
End Sub

'************************************************************************************
'
'  Summary: Move elements down in the XML.
'  
'
'************************************************************************************
Public Sub MoveElementDown(ByVal book As XmlNode)
    ' Walk backwards until we find an element - ignore text nodes
    Dim NextNode As XmlNode = book.NextSibling

    While ((Not (NextNode) Is Nothing) _
                AndAlso (NextNode.NodeType <> XmlNodeType.Element))
        NextNode = NextNode.NextSibling

    End While

    If (Not (NextNode) Is Nothing) Then
        Dim newLineNode As XmlNode = book.PreviousSibling
        book.OwnerDocument.DocumentElement.RemoveChild(book)

        If ((newLineNode.NodeType = XmlNodeType.Whitespace) _
                    Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode)
        End If

        InsertBookElement(CType(book, XmlElement), Constants.positionBelow,
                          NextNode, False, False)
    End If
End Sub

コンストラクター

XmlDocument()

XmlDocument クラスの新しいインスタンスを初期化します。

XmlDocument(XmlImplementation)

XmlDocument を指定して、XmlImplementation クラスの新しいインスタンスを初期化します。

XmlDocument(XmlNameTable)

XmlDocument を指定して、XmlNameTable クラスの新しいインスタンスを初期化します。

プロパティ

Attributes

このノードの属性を格納している XmlAttributeCollection を取得します。

(継承元 XmlNode)
BaseURI

現在のノードのベース URI を取得します。

ChildNodes

ノードのすべての子ノードを取得します。

(継承元 XmlNode)
DocumentElement

ドキュメントのルート XmlElement を取得します。

DocumentType

DOCTYPE 宣言を格納しているノードを取得します。

FirstChild

ノードの最初の子を取得します。

(継承元 XmlNode)
HasChildNodes

このノードに子ノードがあるかどうかを示す値を取得します。

(継承元 XmlNode)
Implementation

現在のドキュメントの XmlImplementation オブジェクトを取得します。

InnerText

常に InvalidOperationException をスローします。

InnerText

ノードとそのすべての子の連結された値を取得または設定します。

(継承元 XmlNode)
InnerXml

現在のノードの子を表すマークアップを取得または設定します。

IsReadOnly

現在のノードが読み取り専用かどうかを示す値を取得します。

Item[String, String]

指定した LocalName および NamespaceURI の最初の子要素を取得します。

(継承元 XmlNode)
Item[String]

指定した Name の最初の子要素を取得します。

(継承元 XmlNode)
LastChild

ノードの最後の子を取得します。

(継承元 XmlNode)
LocalName

ノードのローカル名を取得します。

Name

ノードの限定名を取得します。

NamespaceURI

このノードの名前空間 URI を取得します。

(継承元 XmlNode)
NameTable

この実装に関連付けられている XmlNameTable を取得します。

NextSibling

このノードの直後のノードを取得します。

(継承元 XmlNode)
NodeType

現在のノードの種類を取得します。

OuterXml

このノードとそのすべての子ノードを格納しているマークアップを取得します。

(継承元 XmlNode)
OwnerDocument

現在のノードが属する XmlDocument を取得します。

ParentNode

このノードの親ノード (親を持つノードの場合) を取得します。

ParentNode

このノードの親 (親を持つノードの場合) を取得します。

(継承元 XmlNode)
Prefix

このノードの名前空間プリフィックスを取得または設定します。

(継承元 XmlNode)
PreserveWhitespace

要素のコンテンツにある空白を保存するかどうかを示す値を取得または設定します。

PreviousSibling

このノードの直前のノードを取得します。

(継承元 XmlNode)
PreviousText

このノードの直前にあるテキスト ノードを取得します。

(継承元 XmlNode)
SchemaInfo

ノードの PSVI (Post-Schema-Validation-Infoset) を返します。

SchemaInfo

スキーマ検証の結果、このノードに割り当てられているスキーマ検証後の infoset を取得します。

(継承元 XmlNode)
Schemas

この XmlDocument に関連付けられている XmlSchemaSet オブジェクトを取得または設定します。

Value

ノードの値を取得または設定します。

(継承元 XmlNode)
XmlResolver

外部リソースを解決するために使用する XmlResolver を設定します。

メソッド

AppendChild(XmlNode)

このノードの子ノードのリストの末尾に、指定したノードを追加します。

(継承元 XmlNode)
Clone()

このノードの複製を作成します。

(継承元 XmlNode)
CloneNode(Boolean)

このノードの複製を作成します。

CreateAttribute(String)

指定した Name を使用して XmlAttribute を作成します。

CreateAttribute(String, String)

指定した限定名と NamespaceURI を使用して XmlAttribute を作成します。

CreateAttribute(String, String, String)

指定した PrefixLocalName、および NamespaceURI を使用して、XmlAttribute を作成します。

CreateCDataSection(String)

指定されたデータを格納している XmlCDataSection を作成します。

CreateComment(String)

指定されたデータを格納している XmlComment を作成します。

CreateDefaultAttribute(String, String, String)

指定したプリフィックス、ローカル名、および名前空間 URI の既定の属性を作成します。

CreateDocumentFragment()

XmlDocumentFragment を作成します。

CreateDocumentType(String, String, String, String)

新しい XmlDocumentType オブジェクトを返します。

CreateElement(String)

指定した名前を使用して要素を作成します。

CreateElement(String, String)

限定名と NamespaceURI を使用して XmlElement を作成します。

CreateElement(String, String, String)

指定した PrefixLocalName、および NamespaceURI を使用して、要素を作成します。

CreateEntityReference(String)

指定した名前を使用して、XmlEntityReference を作成します。

CreateNavigator()

このドキュメント内を移動するための、新しい XPathNavigator オブジェクトを作成します。

CreateNavigator()

このオブジェクト内を移動するための XPathNavigator を作成します。

(継承元 XmlNode)
CreateNavigator(XmlNode)

指定した XmlNode に配置されているこのドキュメント内を移動するための XPathNavigator オブジェクトを作成します。

CreateNode(String, String, String)

指定したノード型、Name、および NamespaceURI を使用して、XmlNode を作成します。

CreateNode(XmlNodeType, String, String)

指定した XmlNodeTypeName、および NamespaceURI を使用して、XmlNode を作成します。

CreateNode(XmlNodeType, String, String, String)

指定した XmlNodeTypePrefixName、および NamespaceURI を使用して、XmlNode を作成します。

CreateProcessingInstruction(String, String)

指定した名前とデータを使用して XmlProcessingInstruction を作成します。

CreateSignificantWhitespace(String)

XmlSignificantWhitespace ノードを作成します。

CreateTextNode(String)

指定したテキストを使用して、XmlText を作成します。

CreateWhitespace(String)

XmlWhitespace ノードを作成します。

CreateXmlDeclaration(String, String, String)

指定した値を使用して、XmlDeclaration ノードを作成します。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetElementById(String)

指定した ID の XmlElement を取得します。

GetElementsByTagName(String)

指定した Name に一致するすべての子孫の要素のリストを格納している XmlNodeList を返します。

GetElementsByTagName(String, String)

指定した LocalName および NamespaceURI に一致するすべての子孫の要素のリストを格納している XmlNodeList を返します。

GetEnumerator()

現在のノード内の子ノードを反復処理する列挙子を取得します。

(継承元 XmlNode)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetNamespaceOfPrefix(String)

現在のノードのスコープ内にある指定したプレフィックスに対する最も近い xmlns 宣言を検索し、宣言内の名前空間 URI を返します。

(継承元 XmlNode)
GetPrefixOfNamespace(String)

現在のノードのスコープ内にある指定した名前空間 URI に対する最も近い xmlns 宣言を検索し、宣言で定義されているプレフィックスを返します。

(継承元 XmlNode)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
ImportNode(XmlNode, Boolean)

別のドキュメントから現在のドキュメントにノードをインポートします。

InsertAfter(XmlNode, XmlNode)

指定したノードを指定した参照ノードの直後に挿入します。

(継承元 XmlNode)
InsertBefore(XmlNode, XmlNode)

指定したノードを指定した参照ノードの直前に挿入します。

(継承元 XmlNode)
Load(Stream)

指定したストリームから XML ドキュメントを読み込みます。

Load(String)

指定した URL から XML ドキュメントを読み込みます。

Load(TextReader)

指定した TextReader から XML ドキュメントを読み込みます。

Load(XmlReader)

指定した XmlReader から XML ドキュメントを読み込みます。

LoadXml(String)

指定した文字列から XML ドキュメントを読み込みます。

MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
Normalize()

この XmlNode の一番下のサブツリーまで含め、すべての XmlText ノードをマークアップ (タグ、コメント、処理命令、CDATA セクション、およびエンティティ参照) だけが XmlText ノードを区分する "通常の" 書式にします。したがって、隣接する XmlText ノードはありません。

(継承元 XmlNode)
PrependChild(XmlNode)

このノードの子ノードのリストの先頭に、指定したノードを追加します。

(継承元 XmlNode)
ReadNode(XmlReader)

XmlReader 内の情報に基づいて、XmlNode オブジェクトを作成します。 リーダーは、ノードまたは属性に配置されている必要があります。

RemoveAll()

現在のノードのすべての子ノードと属性の両方、またはそのいずれかを削除します。

(継承元 XmlNode)
RemoveChild(XmlNode)

指定した子ノードを削除します。

(継承元 XmlNode)
ReplaceChild(XmlNode, XmlNode)

子ノード oldChildnewChild ノードに置き換えます。

(継承元 XmlNode)
Save(Stream)

指定したストリームに XML ドキュメントを保存します。

Save(String)

指定したファイルに XML ドキュメントを保存します。 指定したファイルが存在する場合は、このメソッドはそれを上書きします。

Save(TextWriter)

指定した TextWriter に XML ドキュメントを保存します。

Save(XmlWriter)

指定した XmlWriter に XML ドキュメントを保存します。

SelectNodes(String)

XPath 式と一致するノードのリストを選択します。

(継承元 XmlNode)
SelectNodes(String, XmlNamespaceManager)

XPath 式と一致するノードのリストを選択します。 XPath 式で見つかったプリフィックスは、指定した XmlNamespaceManager を使用して解決されます。

(継承元 XmlNode)
SelectSingleNode(String)

XPath 式と一致する最初の XmlNode を選択します。

(継承元 XmlNode)
SelectSingleNode(String, XmlNamespaceManager)

XPath 式と一致する最初の XmlNode を選択します。 XPath 式で見つかったプリフィックスは、指定した XmlNamespaceManager を使用して解決されます。

(継承元 XmlNode)
Supports(String, String)

DOM 実装が特定の機能を実装するかどうかをテストします。

(継承元 XmlNode)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)
Validate(ValidationEventHandler)

Schemas プロパティに格納されている XML スキーマ定義言語 (XSD) スキーマと照合して XmlDocument を検証します。

Validate(ValidationEventHandler, XmlNode)

Schemas プロパティの XML スキーマ定義言語 (XSD) スキーマと照合し、指定された XmlNode オブジェクトを検証します。

WriteContentTo(XmlWriter)

指定した XmlWriterXmlDocument ノードのすべての子を保存します。

WriteTo(XmlWriter)

指定した XmlWriterXmlDocument ノードを保存します。

events

NodeChanged

このドキュメントに属するノードの Value が変更されると発生します。

NodeChanging

このドキュメントに属するノードの Value が変更される直前に発生します。

NodeInserted

このドキュメントに属するノードが別のノードに挿入されると発生します。

NodeInserting

このドキュメントに属するノードが別のノードに挿入される直前に発生します。

NodeRemoved

このドキュメントに属するノードが親から削除されると発生します。

NodeRemoving

このドキュメントに属するノードがドキュメントから削除される直前に発生します。

明示的なインターフェイスの実装

ICloneable.Clone()

このメンバーの詳細については、「Clone()」をご覧ください。

(継承元 XmlNode)
IEnumerable.GetEnumerator()

このメンバーの詳細については、「GetEnumerator()」をご覧ください。

(継承元 XmlNode)

拡張メソッド

Cast<TResult>(IEnumerable)

IEnumerable の要素を、指定した型にキャストします。

OfType<TResult>(IEnumerable)

指定された型に基づいて IEnumerable の要素をフィルター処理します。

AsParallel(IEnumerable)

クエリの並列化を有効にします。

AsQueryable(IEnumerable)

IEnumerableIQueryable に変換します。

CreateNavigator(XmlDocument)

指定されたドキュメント内を移動するための新しい XPath ナビゲーター オブジェクトを作成します。

CreateNavigator(XmlDocument, XmlNode)

指定されたノード上に配置された、指定されたドキュメント内を移動するための XPath ナビゲーター オブジェクトを作成します。

CreateNavigator(XmlNode)

指定したノードをナビゲートするための XPath ナビゲーターを作成します。

SelectNodes(XmlNode, String)

指定した XPath 式と一致するノードのリストを選択します。

SelectNodes(XmlNode, String, XmlNamespaceManager)

指定した XPath 式と一致するノードのリストを選択します。 XPath 式で見つかったプリフィックスは、指定した名前空間マネージャーを使用して解決されます。

SelectSingleNode(XmlNode, String)

XPath 式と一致する最初のノードを選択します。

SelectSingleNode(XmlNode, String, XmlNamespaceManager)

XPath 式と一致する最初のノードを選択します。 XPath 式で見つかったプリフィックスは、指定した名前空間マネージャーを使用して解決されます。

ToXPathNavigable(XmlNode)

ナビゲーターを生成するために使用する IXPathNavigable インスタンスを作成します。

適用対象

こちらもご覧ください