ホームページ >バックエンド開発 >C++ >C# の XmlDocument を使用して XML 属性にアクセスする方法

C# の XmlDocument を使用して XML 属性にアクセスする方法

Linda Hamilton
Linda Hamiltonオリジナル
2025-01-06 09:25:40576ブラウズ

How to Access XML Attributes Using C#'s XmlDocument?

XmlDocument を使用した XML 属性へのアクセス

C# の XmlDocument を使用した XML 属性の読み取りは、簡単なアプローチで実現できます。次の XML ドキュメントについて考えてみましょう。

<?xml version="1.0" encoding="utf-8" ?>
<MyConfiguration xmlns="http://tempuri.org/myOwnSchema.xsd" SuperNumber="1" SuperString="whipcream">
    <Other stuff />
</MyConfiguration>

属性 SuperNumber および SuperString を取得するには、次のコードを利用できます。

// Load the XML document
XmlDocument doc = new XmlDocument();
doc.Load("myConfig.xml");

// Get the specified element by its tag name
XmlNodeList elemList = doc.GetElementsByTagName("MyConfiguration");

// Iterate through the matching elements
for (int i = 0; i < elemList.Count; i++)
{
    // Access the attribute value
    string attrVal = elemList[i].Attributes["SuperString"].Value;
}

このコード スニペットは、GetElementsByTagName メソッドを使用して MyConfiguration を検索します。要素。次に、結果のリストを反復処理し、Attributes プロパティを使用して「SuperString」属性にアクセスします。属性オブジェクトの Value プロパティは、実際の属性値を提供します。

このアプローチを利用すると、C# の XmlDocument クラスを使用して XML 属性を簡単に読み取り、処理できます。

以上がC# の XmlDocument を使用して XML 属性にアクセスする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。