특성은 요소의 자식이 아니라 요소의 속성입니다. 이 구분은 XML DOM(문서 개체 모델)의 형제, 부모 및 자식 노드를 탐색하는 데 사용되는 메서드 때문에 중요합니다. 예를 들어 PreviousSibling 및 NextSibling 메서드는 요소에서 특성으로 또는 특성 간에 탐색하는 데 사용되지 않습니다. 대신 특성은 요소의 속성이며 요소가 소유하고 parentNode 속성이 아닌 OwnerElement 속성을 가지며 고유한 탐색 메서드를 가집니다.
현재 노드가 요소인 경우 HasAttribute 메서드를 사용하여 요소와 연결된 특성이 있는지 확인합니다. 요소에 특성이 있다는 것이 알려지면 특성에 액세스하는 여러 메서드가 있습니다. 요소에서 단일 특성을 검색하려면 XmlElement의 GetAttribute 및 GetAttributeNode 메서드를 사용하거나 컬렉션에 모든 특성을 가져올 수 있습니다. 컬렉션을 반복해야 하는 경우 컬렉션을 획득하는 것이 유용합니다. 요소의 모든 특성을 원하는 경우 요소의 Attributes 속성을 사용하여 모든 특성을 컬렉션으로 검색합니다.
컬렉션에 모든 특성 검색
요소 노드의 모든 특성을 컬렉션에 넣으려면 XmlElement.Attributes 속성을 호출합니다. 요소의 모든 특성을 포함하는 XmlAttributeCollection 을 가져옵니다. XmlAttributeCollection 클래스는 XmlNamedNode 맵에서 상속됩니다. 따라서 컬렉션에서 사용할 수 있는 메서드와 속성에는 ItemOf 속성 또는 Append 메서드와 같은 XmlAttributeCollection 클래스와 관련된 메서드 및 속성 외에도 명명된 노드 맵에서 사용할 수 있는 메서드와 속성이 포함됩니다. 특성 컬렉션의 각 항목은 XmlAttribute 노드를 나타냅니다. 요소의 특성 수를 찾으려면 XmlAttributeCollection을 가져와 서 Count 속성을 사용하여 컬렉션에 있는 XmlAttribute 노드 수를 확인합니다.
다음 코드 예제에서는 특성 컬렉션을 검색하고 루프 인덱스용 Count 메서드를 사용하여 반복하는 방법을 보여줍니다. 그런 다음 이 코드는 컬렉션에서 단일 특성을 검색하고 해당 값을 표시하는 방법을 보여줍니다.
Imports System.IO
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5' misc='sale item'>" & _
"<title>The Handmaid's Tale</title>" & _
"<price>14.95</price>" & _
"</book>")
' Move to an element.
Dim myElement As XmlElement = doc.DocumentElement
' Create an attribute collection from the element.
Dim attrColl As XmlAttributeCollection = myElement.Attributes
' Show the collection by iterating over it.
Console.WriteLine("Display all the attributes in the collection...")
Dim i As Integer
For i = 0 To attrColl.Count - 1
Console.Write("{0} = ", attrColl.ItemOf(i).Name)
Console.Write("{0}", attrColl.ItemOf(i).Value)
Console.WriteLine()
Next
' Retrieve a single attribute from the collection; specifically, the
' attribute with the name "misc".
Dim attr As XmlAttribute = attrColl("misc")
' Retrieve the value from that attribute.
Dim miscValue As String = attr.InnerXml
Console.WriteLine("Display the attribute information.")
Console.WriteLine(miscValue)
End Sub
End Class
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5' misc='sale item'>" +
"<title>The Handmaid's Tale</title>" +
"<price>14.95</price>" +
"</book>");
// Move to an element.
XmlElement myElement = doc.DocumentElement;
// Create an attribute collection from the element.
XmlAttributeCollection attrColl = myElement.Attributes;
// Show the collection by iterating over it.
Console.WriteLine("Display all the attributes in the collection...");
for (int i = 0; i < attrColl.Count; i++)
{
Console.Write("{0} = ", attrColl[i].Name);
Console.Write("{0}", attrColl[i].Value);
Console.WriteLine();
}
// Retrieve a single attribute from the collection; specifically, the
// attribute with the name "misc".
XmlAttribute attr = attrColl["misc"];
// Retrieve the value from that attribute.
String miscValue = attr.InnerXml;
Console.WriteLine("Display the attribute information.");
Console.WriteLine(miscValue);
}
}
이 예제에서는 다음 출력을 표시합니다.
출력
컬렉션의 모든 특성을 표시합니다.
genre = novel
ISBN = 1-861001-57-5
misc = sale item
Display the attribute information.
sale item
특성 컬렉션의 정보는 이름 또는 인덱스 번호로 검색할 수 있습니다. 위의 예제에서는 이름으로 데이터를 검색하는 방법을 보여 있습니다. 다음 예제에서는 인덱스 번호로 데이터를 검색하는 방법을 보여줍니다.
XmlAttributeCollection은 컬렉션이며 이름 또는 인덱스로 반복될 수 있으므로 이 예제에서는 0부터 시작하는 인덱스를 사용하여 컬렉션에서 첫 번째 특성을 선택하고 다음 파일 인baseuri.xml입력으로 사용하는 방법을 보여 드립니다.
입력
<!-- XML fragment -->
<book genre="novel">
<title>Pride And Prejudice</title>
</book>
Option Explicit On
Option Strict On
Imports System.IO
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
' Create the XmlDocument.
Dim doc As New XmlDocument()
doc.Load("http://localhost/baseuri.xml")
' Display information on the attribute node. The value
' returned for BaseURI is 'http://localhost/baseuri.xml'.
Dim attr As XmlAttribute = doc.DocumentElement.Attributes(0)
Console.WriteLine("Name of the attribute: {0}", attr.Name)
Console.WriteLine("Base URI of the attribute: {0}", attr.BaseURI)
Console.WriteLine("The value of the attribute: {0}", attr.InnerText)
End Sub 'Main
End Class 'Sample
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("http://localhost/baseuri.xml");
// Display information on the attribute node. The value
// returned for BaseURI is 'http://localhost/baseuri.xml'.
XmlAttribute attr = doc.DocumentElement.Attributes[0];
Console.WriteLine("Name of the attribute: {0}", attr.Name);
Console.WriteLine("Base URI of the attribute: {0}", attr.BaseURI);
Console.WriteLine("The value of the attribute: {0}", attr.InnerText);
}
}
개별 특성 노드 검색
요소에서 단일 특성 노드를 검색하기 위해 메서드가 XmlElement.GetAttributeNode 사용됩니다. XmlAttribute 형식의 개체를 반환합니다. XmlAttribute가 있으면 System.Xml.XmlAttribute 찾기와 같이 클래스에서 사용할 수 있는 모든 메서드와 속성을 해당 개체에서 사용할 수 있습니다.
Imports System.IO
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5' misc='sale item'>" & _
"<title>The Handmaid's Tale</title>" & _
"<price>14.95</price>" & _
"</book>")
' Move to an element.
Dim root As XmlElement
root = doc.DocumentElement
' Get an attribute.
Dim attr As XmlAttribute
attr = root.GetAttributeNode("ISBN")
' Display the value of the attribute.
Dim attrValue As String
attrValue = attr.InnerXml
Console.WriteLine(attrValue)
End Sub
End Class
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861003-78' misc='sale item'>" +
"<title>The Handmaid's Tale</title>" +
"<price>14.95</price>" +
"</book>");
// Move to an element.
XmlElement root = doc.DocumentElement;
// Get an attribute.
XmlAttribute attr = root.GetAttributeNode("ISBN");
// Display the value of the attribute.
String attrValue = attr.InnerXml;
Console.WriteLine(attrValue);
}
}
특성 컬렉션에서 단일 특성 노드를 검색하는 이전 예제와 같이 수행할 수도 있습니다. 다음 코드 예제에서는 한 줄의 코드를 작성하여 DOCUMENTElement 속성이라고도 하는 XML 문서 트리의 루트에서 인덱스 번호로 단일 특성을 검색하는 방법을 보여줍니다.
XmlAttribute attr = doc.DocumentElement.Attributes[0];
참고하십시오
.NET