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>
XML 속성 SuperNumber 및 SuperString을 어떻게 읽습니까?
현재 저는 XmlDocument를 사용 GetElementsByTagName()
하고 있으며 XmlDocument를 사용하는 사이에 값을 얻었으며 실제로 잘 작동합니다. 속성을 얻는 방법을 알 수 없습니까?
답변
XmlNodeList elemList = doc.GetElementsByTagName(...);
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["SuperString"].Value;
}
답변
XPath를 살펴 봐야 합니다. 일단 사용을 시작하면 목록을 반복하는 것보다 훨씬 효율적이고 코딩하기 쉽습니다. 또한 원하는 것을 직접 얻을 수 있습니다.
그러면 코드는 다음과 유사합니다.
string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;
XPath 3.0은 2014 년 4 월 8 일에 W3C 권장 사항이되었습니다.
답변
XmlDocument 대신 XDocument로 마이그레이션 한 다음 해당 구문을 선호하는 경우 Linq를 사용할 수 있습니다. 다음과 같은 것 :
var q = (from myConfig in xDoc.Elements("MyConfiguration")
select myConfig.Attribute("SuperString").Value)
.First();
답변
Xml 파일 books.xml이 있습니다.
<ParameterDBConfig>
<ID Definition="1" />
</ParameterDBConfig>
프로그램:
XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["Definition"].Value;
}
이제 attrVal
값은 ID
.
답변
XmlDocument.Attributes
혹시? (항상 속성 컬렉션을 반복했지만 원하는 것을 수행 할 수있는 GetNamedItem 메서드가 있습니다.)
답변
예제 문서가 문자열 변수에 있다고 가정합니다. doc
> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1
답변
XML에 네임 스페이스가 포함 된 경우 속성 값을 얻기 위해 다음을 수행 할 수 있습니다.
var xmlDoc = new XmlDocument();
// content is your XML as string
xmlDoc.LoadXml(content);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
// make sure the namespace identifier, URN in this case, matches what you have in your XML
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:SAML:2.0:protocol");
// get the value of Destination attribute from within the Response node with a prefix who's identifier is "urn:oasis:names:tc:SAML:2.0:protocol" using XPath
var str = xmlDoc.SelectSingleNode("/ns:Response/@Destination", nsmgr);
if (str != null)
{
Console.WriteLine(str.Value);
}
