2010-12-06 76 views
2

這可能是一些非常簡單的,但我不能讓我的頭周圍這樣的幫助,將不勝感激:)問題在LINQ查詢使用.value的

我有,我想解析一個簡單的XML文件我訪問元素的值時遇到問題。

這是XML文檔,我有:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<application> 
    <description> 
     <![CDATA[ This is the description of the application. ]]> 
    </description>  
    <parameters> 
     <param type="int32" name="testvar1" required="false">10</param> 
     <param type="string" name="testvar2" required="true" /> 
     <param type="float" name="testvar3">42.00</param> 
    </parameters> 
</application> 

我從一個文本框加載文檔,如:

var doc = XDocument.Parse(textBox1.Text); 

而且我用一個簡單的LINQ查詢,以過濾掉的東西:

var parameters = from param in doc.Descendants("param") 
       select new 
       { 
        name = (String)param.Attribute("name"), 
        type = (String)param.Attribute("type"), 
        value = (String)param.Value, // Wrong? 
       }; 

var data = String.Empty; 
foreach (var p in parameters) 
{ 
    data += p.name; 
    data += " -- "; 
    data += p.type; 
    data += " -- "; 
    data += p.value; 
    data += "\n\r"; 
} 

輸出結果如下:

testvar1 -- int32 -- 
testvar2 -- string -- 
testvar3 -- float -- 

換句話說,行value = (String)param.Value似乎沒有預期的效果。

編輯:這似乎是我沒有閱讀正確的XML文件,我的壞。下面的問題仍然是,雖然有效...

此外,下面的行會導致一個NullReferenceException:

var description = (String) doc.Element("description").Value; 

所以看起來我不太明白如何讓XML元素的值:)你能幫我解決這些問題嗎?

謝謝。

回答

0

我是有問題的:

var description = doc.Element("application").Element("description").Value; 

var description = doc.Element("description").Value; 

但是這一次似乎工作:

var description = doc.Descendants("description").First().Value; 
0

XElement.Valuestring所以既不要求也不要求鑄(string)也不要ToString()


使用

doc.Element("application").Element("description").Value 

獲得描述值


foreach (var p in parameters) 
{ 
    Console.WriteLine("name={0} type={1} value={2}", p.name, p.type, p.value); 
} 

輸出下一:

name=testvar1 type=int32 value=10 
name=testvar2 type=string value= 
name=testvar3 type=float value=42.00 

所以你的c頌歌對我有用。

+0

謝謝你的答案,但有或沒有投我還沒有看到任何輸出。 – Hamza 2010-12-06 15:52:08

+0

@Hamza:查看我的更新後文章 – abatishchev 2010-12-06 15:56:48

0

,因爲我只是跑你的代碼,並得到

testvar1奇怪 - INT32 - 10
testvar2 - 字符串 -
testvar3 - 浮 - 42。00

有或無的param.Value

字符串投拿到描述,你可以做

doc.Element("application").Element("description").Value;