2016-09-25 21 views
1

說我有這樣的:更快/更短的方式來獲得屬性的中的XElement在C#中指定的屬性值

<my-element> 
    <property name="the property name" value="the value"/> 
    <property name="some other property name" value="other value"/> 
</my-element> 

我用下面的代碼獲取「值」從名稱等於「屬性名稱」的房產

string theValue = (
    from p 
    in myElement.Elements("Property") 
    where p.Attribute("name").Value == "the property name" 
    select p.Attribute("value").Value 
).FirstOrDefault(); 

這段代碼可以完成這項工作,但我想知道是否有更好的方法來做到這一點。

回答

0

我不知道這主觀更好的辦法,但你也可以使用的XPath

var xDoc = XDocument.Parse(xmlstring); 
var val = (string)xDoc.XPathSelectElement("//property[@name='the property name']") 
         .Attribute("value"); 
+0

謝謝,我結束了使用'XPathSelectElement(「/ * /屬性[@名稱='預製']「)',你建議的XPath會給我一些問題。還嘗試過'XPathEvaluate(「/ */Property [@ name ='prefab']/@ value」)'但是也沒有工作。我認爲這些錯誤可能與[Unity版附帶的庫](http://stackoverflow.com/q/24978146/1436359)有關。 – rraallvv