[英]LINQ to XML C# get root element attribute
Lts 說我有 XElement object 文檔:
<parameters mode="solve">
<inputs>
<a>value_a</a>
...
...
我如何獲取第一個元素(參數)的屬性值,換句話說,我如何檢查它處於哪種模式。
如果我寫
if ((string)doc.Element("parameters").Attribute("mode").Value == "solve") { mode = 1; }
它給了我 null object 參考錯誤
如果doc
是XElement
,正如您在問題中所說,那么您可能不需要再次匹配它:
if (doc.Attribute("mode").Value.ToString() == "solve") {
mode = 1;
}
如果它是XDocument
,那么您可以使用它的Root屬性來引用文檔元素:
if (doc.Root.Attribute("mode").Value.ToString() == "solve") {
mode = 1;
}
只需使用Root
if (doc.Root.Attribute("mode").Value.Equals("solve"))
{
mode = 1;
}
當您調用doc.Element("parameters")
時,您正在嘗試查看根元素下方的元素(在這種情況下,與<inputs>
處於同一級別的元素)。 你想這樣做:
if (input.Attribute("mode").Value == "solve") { mode = 1; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.