2009-06-01 75 views
67

如何使用C#的XmlDocument讀取XML屬性?使用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和超弦理論?

目前我使用的是XmlDocument,並且我使用XmlDocument的GetElementsByTagName()獲得了兩者之間的值,這非常適用。我只是不知道如何獲得屬性?

回答

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

太感謝你了。它確實有效,它不需要任何路徑,也不需要任何東西。簡直棒極了! – Nani 2016-10-19 10:32:42

5

XmlDocument.Attributes也許? (其中有一個方法GetNamedItem,將可能做你想做的,但我一直只是重複的屬性集合)

81

你應該看看XPath。一旦你開始使用它,你會發現它比遍歷列表更有效,更容易編碼。它也可以讓你直接得到你想要的東西。

然後代碼將是類似的東西,以

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

可以遷移到的XDocument代替的XmlDocument,然後使用Linq如果你喜歡的語法。喜歡的東西:

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

我有一個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; 
} 

attrValID值。

1

假設您的示例文件是字符串變量doc

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

如果你的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); 
} 

有關XML名稱空間的更多信息,請參閱herehere

0

我已經做到了這一點:

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