C #에서 XmlNode에서 특성 값을 읽는 방법은 무엇입니까?


114

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>

답변:


214

이 시도:

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

편집 : 주석에서 지적했듯이 속성이 존재하지 않으면 예외가 발생합니다. 안전한 방법은 다음과 같습니다.

var attribute = node.Attributes["Name"];
if (attribute != null){
    string employeeName = attribute.Value;
    // Process the value here
}

34
이 접근 방식에주의하십시오. 속성이 없으면 Value 멤버에 액세스하면 Null 참조 예외가 발생한다고 생각합니다.
Chris Dunaway

3
if (node.Attributes! = null) string employeeName = chldNode.Attributes [ "Name"]. Value;
Omidoo

7
@Omidoo 그 접근 방식은 예를 들어 <a x="1" />테스트를 통과하는 에서 동일한 문제가 있습니다. 아마도 같은 var attr = node.Attributes["Name"]; if(attr != null) {...}것이 작동 할 것입니다.
Joel Peltonen 2012

NullException 문제를 우회하고 사용하는 것이 더 안전 할 수있는 아래의 내 대답을 살펴보십시오 .
Marco7757

44

Konamiman의 솔루션 (모든 관련 null 검사 포함)을 확장하기 위해 다음과 같이했습니다.

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

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

6
? 널 (null)에 대한 오류가 발생하지의 속기 방법이 node.Attributes이다 "이름"]? 값
brandonstrong

1
또한 사실, 내가 지적 할 유일한 것은 한 줄로 할 수 있지만 (할당이나 무언가에 좋게 만드는), 예외를 던지거나 다른 방식으로 처리 할 때 제어 측면에서 약간 덜 유연하다는 것입니다. 노드에 속성이없는 경우.
Ari Roth

1
동의합니다. 속기 방식을 사용하는 사람은 항상 다운 스트림 문제를 일으키지 않는지 확인해야합니다.
brandonstrong

17

노드에서하는 것처럼 모든 속성을 반복 할 수 있습니다.

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

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

이것은 더 바람직 할 것입니다 .. :)
SHEKHAR SHETE

4

이름 만 있으면 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");

위의 방법은 내 XML에서 작동하지 않았습니다. 이 방법은 그렇습니다! 감사!
Frecklefoot

4

대신 chldNodeas 를 사용하면 다음을 사용할 수 있습니다.XmlElementXmlNode

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

사용하다

item.Attributes["Name"].Value;

가치를 얻으려면.


1

이것을 사용할 수도 있습니다.

string employeeName = chldNode.Attributes().ElementAt(0).Name

1

또 다른 해결책 :

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

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

또한 예상 속성이 attributeName실제로 존재하지 않을 때 예외를 방지 합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.