web-dev-qa-db-ja.com

C#でXmlNodeから属性値を読み取る方法は?

XmlNodeがあり、「Name」という名前の属性の値を取得するとします。どうやってやるの?

XmlTextReader reader = new XmlTextReader(path);

XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);

foreach (XmlNode chldNode in node.ChildNodes)
{
     **//Read the attribute Name**
     if (chldNode.Name == Employee)
     {                    
         if (chldNode.HasChildNodes)
         {
             foreach (XmlNode item in node.ChildNodes)
             { 

             }
         }
      }
}

XMLドキュメント:

<Root>
    <Employee Name ="TestName">
    <Childs/>
</Root>
104
Ashish Ashu

これを試して:

string employeeName = chldNode.Attributes["Name"].Value;
194
Konamiman

コナミマンのソリューション(関連するすべてのnullチェックを含む)を拡張するために、これは私がやっていることです:

if (node.Attributes != null)
{
   var nameAttribute = node.Attributes["Name"];
   if (nameAttribute != null) 
      return nameAttribute.Value;

   throw new InvalidOperationException("Node 'Name' not found.");
}
42
Ari Roth

ノードと同じように、すべての属性をループできます

foreach (XmlNode item in node.ChildNodes)
{ 
    // node stuff...

    foreach (XmlAttribute att in item.Attributes)
    {
        // attribute stuff
    }
}
17
balexandre

名前だけが必要な場合は、代わりにxpathを使用します。自分で繰り返しを行ってnullをチェックする必要はありません。

string xml = @"
<root>
    <Employee name=""an"" />
    <Employee name=""nobyd"" />
    <Employee/>
</root>
";

var doc = new XmlDocument();

//doc.Load(path);
doc.LoadXml(xml);

var names = doc.SelectNodes("//Employee/@name");
4
an phu

つかいます

item.Attributes["Name"].Value;

値を取得します。

3
rahul

chldNodeの代わりにXmlElementとしてXmlNodeを使用する場合、次を使用できます。

var attributeValue = chldNode.GetAttribute("Name");

戻り値は空の​​文字列になります 、属性名が存在しない場合。

したがって、ループは次のようになります。

XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");

foreach (XmlElement node in nodes)
{
    var attributeValue = node.GetAttribute("Name");
}

これにより、<node>タグで囲まれたすべてのノード<Node><N0de></N0de><Node>が選択され、その後それらをループして属性「名前」を読み取ります。

3
Marco7757

さらに別のソリューション:

string s = "??"; // or whatever

if (chldNode.Attributes.Cast<XmlAttribute>()
                       .Select(x => x.Value)
                       .Contains(attributeName))   
   s =  xe.Attributes[attributeName].Value;

また、期待される属性attributeNameが実際に存在しない場合の例外を回避します。

1
TaW

これも使用できます。

string employeeName = chldNode.Attributes().ElementAt(0).Name
1
cell-in