Odczyt atrybutu XML przy użyciu XmlDocument

Jak mogę odczytać atrybut XML używając XmlDocument C#?

Mam plik XML, który wygląda mniej więcej tak:

<?xml version="1.0" encoding="utf-8" ?>
<MyConfiguration xmlns="http://tempuri.org/myOwnSchema.xsd" SuperNumber="1" SuperString="whipcream">
    <Other stuff />
</MyConfiguration> 

Jak odczytać atrybuty XML SuperNumber i SuperString?

Obecnie używam XmlDocument, i dostaję wartości pomiędzy używaniem GetElementsByTagName() XmlDocument i to działa naprawdę dobrze. Po prostu nie mogę wymyślić, jak zdobyć atrybuty?

Author: John Saunders, 2009-06-01

7 answers

XmlNodeList elemList = doc.GetElementsByTagName(...);
for (int i = 0; i < elemList.Count; i++)
{
    string attrVal = elemList[i].Attributes["SuperString"].Value;
}
 115
Author: Arsen Mkrtchyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-21 08:10:51

Powinieneś zajrzeć do XPath . Gdy zaczniesz go używać, okaże się, że jest o wiele bardziej wydajny i łatwiejszy do kodowania niż iteracja przez listy. Pozwala również bezpośrednio uzyskać to, co chcesz.

Wtedy kod byłby czymś podobnym do

string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;

Zauważ, że XPath 3.0 stał się rekomendacją W3C 8 kwietnia 2014 roku.

 88
Author: Greg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-25 20:11:40

Możesz przenieść do XDocument zamiast XmlDocument, a następnie użyć Linq, jeśli wolisz taką składnię. Coś w stylu:

var q = (from myConfig in xDoc.Elements("MyConfiguration")
         select myConfig.Attribute("SuperString").Value)
         .First();
 8
Author: Matt Sherman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-01 07:23:33

Mam Księgi plików Xml.xml

<ParameterDBConfig>
    <ID Definition="1" />
</ParameterDBConfig>

Program:

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;
}

Teraz attrVal ma wartość ID.

 8
Author: siva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-05 11:38:44

XmlDocument.Attributes może? (Który ma metodę GetNamedItem, która prawdopodobnie zrobi to, co chcesz, chociaż zawsze tylko iterowałem kolekcję atrybutów)

 5
Author: jerryjvl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-01 05:53:48

Zakładając, że przykładowy dokument znajduje się w zmiennej łańcuchowej doc

> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1
 1
Author: Colonel Panic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-17 19:55:43

Jeśli twój XML zawiera przestrzenie nazw, możesz wykonać następujące czynności, aby uzyskać wartość atrybutu:

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);
}

Więcej o przestrzeniach nazw XML tutaj i tutaj.

 1
Author: Voicu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-01 19:47:02