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>
답변
이 시도:
string employeeName = chldNode.Attributes["Name"].Value;
편집 : 주석에서 지적했듯이 속성이 존재하지 않으면 예외가 발생합니다. 안전한 방법은 다음과 같습니다.
var attribute = node.Attributes["Name"];
if (attribute != null){
string employeeName = attribute.Value;
// Process the value here
}
답변
Konamiman의 솔루션 (모든 관련 null 검사 포함)을 확장하기 위해 다음과 같이했습니다.
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["Name"];
if (nameAttribute != null)
return nameAttribute.Value;
throw new InvalidOperationException("Node 'Name' not found.");
}
답변
노드에서하는 것처럼 모든 속성을 반복 할 수 있습니다.
foreach (XmlNode item in node.ChildNodes)
{
// node stuff...
foreach (XmlAttribute att in item.Attributes)
{
// attribute stuff
}
}
답변
이름 만 있으면 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");
답변
대신 chldNode
as 를 사용하면 다음을 사용할 수 있습니다.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>
되고 이후에 이들을 반복하여 “이름”속성을 읽습니다.
답변
사용하다
item.Attributes["Name"].Value;
가치를 얻으려면.
답변
이것을 사용할 수도 있습니다.
string employeeName = chldNode.Attributes().ElementAt(0).Name
