2009-06-01 16 views
67

Come posso leggere un attributo XML utilizzando XmlDocument di C#?Leggi attributo XML utilizzando XmlDocument

Ho un file XML, che sembra un po 'come questo:

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

Come dovrei leggere gli attributi XML SuperNumber e superstringhe?

Attualmente sto usando XmlDocument e ottengo i valori tra l'uso di XmlDocument GetElementsByTagName() e questo funziona davvero bene. Non riesco proprio a capire come ottenere gli attributi?

risposta

96
XmlNodeList elemList = doc.GetElementsByTagName(...); 
for (int i = 0; i < elemList.Count; i++) 
{ 
    string attrVal = elemList[i].Attributes["SuperString"].Value; 
} 
+0

grazie mille. funziona davvero e non ha bisogno di percorsi e nulla. semplicemente fantastico !! – Nani

5

XmlDocument.Attributes forse? (Che ha un metodo getNamedItem che presumibilmente fare quello che vuoi, anche se ho sempre e solo iterato della collezione attributi)

81

Si dovrebbe guardare in XPath. Una volta che inizi a utilizzarlo, scoprirai che è molto più efficiente e facile da codificare rispetto a iterare attraverso gli elenchi. Ti consente anche di ottenere direttamente le cose che desideri.

Quindi il codice sarebbe stato qualcosa di simile a

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

È possibile migrare a XDocument invece di XmlDocument e quindi utilizzare LINQ, se si preferisce che la sintassi. Qualcosa di simile:

var q = (from myConfig in xDoc.Elements("MyConfiguration") 
     select myConfig.Attribute("SuperString").Value) 
     .First(); 
5

Ho un books.xml Xml File

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

Programma:

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

Ora, attrVal ha il valore di ID.

1

Assumendo che il documento di esempio si trova nella variabile stringa doc

> XDocument.Parse(doc).Root.Attribute("SuperNumber") 
1 
0

Se il XML contiene spazi dei nomi, allora si può fare quanto segue al fine di ottenere il valore di un attributo:

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

Ulteriori informazioni sugli spazi dei nomi XML here e here.

0

Ho fatto questo:

XmlDocument d = new XmlDocument(); 
d.Load("http://your.url.here"); 
List<string> items = new List<string>(); 

foreach (XmlAttribute attr in d.DocumentElement.Attributes) 
{ 
    items.Add(attr.LocalName);     
}