[英]How to get xml node in c#?
我正在嘗試從xmldocument獲取成本節點,但是我不知道如何設置正確的xpath表達式。 這是我的C#代碼:
XmlNode n = reportFields.SelectSingleNode(field[1].Trim());
field [1]是我的xpath,以下字符串:
" /Report/Tablix6/RowGroup_Collection/RowGroup/@Cost"
這是reportFields的innerXml屬性的一部分:
"<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Report Name=\"Sample\">
<Tablix6>
<RowGroup_Collection>
<RowGroup Cost=\"1199\" />
</RowGroup_Collection>
</Tablix6>
有任何想法嗎?
編輯:
執行此代碼后,n為空。
EDIT2:這是xmlDocument的更新版本:
<?xml version="1.0" encoding="utf-8" ?>
<Report xsi:schemaLocation="Telephony http://serverName"
Name="Telephony"
Textbox1="Telephony total cost"
Textbox6="Updated: 2010-4"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="Telephony">
<Tablix6>
<RowGroup_Collection>
<RowGroup CostSEK="13.908239364624" />
</RowGroup_Collection>
</Tablix6>
好的,我設法解決了。 原來,我不得不創建一個名稱空間並修改我的XPath字符串以反映這一點:
XPath:
ns:Report/ns:Tablix6/ns:RowGroup_Collection/ns:RowGroup/@CostSEK
C#:
XmlNamespaceManager namespaces = new XmlNamespaceManager(reportFields.NameTable);
namespaces.AddNamespace("ns", "Telephony");
XmlNode n = reportFields.SelectSingleNode(field[1].Trim(), namespaces);
嘗試
XmlNode n = reportFields.SelectSingleNode("/Report/Tablix6/RowGroup_Collection/RowGroup").Attributes["Cost"];
然后,您可以使用n.Value訪問節點的值,因此
Console.Writeline(n.Value);
應該輸出“ 1199”
請試試:
object attr = reportFields.SelectSingleNode(field[1].Trim()).Value;
"//Report/Tablix6/RowGroup_Collection/RowGroup/@Cost"
我可以弄錯,但我認為如果XPath表達式以雙斜杠“ //”開頭會更好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.