0

我正在尝试从 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>
4

4 回答 4

1

好的,我设法解决了它。原来我必须创建一个命名空间并修改我的 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);
于 2012-09-04T10:43:08.653 回答
0

尝试

XmlNode n = reportFields.SelectSingleNode("/Report/Tablix6/RowGroup_Collection/RowGroup").Attributes["Cost"];

然后您可以使用 n.Value 访问节点的值,所以

Console.Writeline(n.Value);

应该输出“1199”

于 2012-09-03T10:16:53.683 回答
0

请试试:

object attr = reportFields.SelectSingleNode(field[1].Trim()).Value;
于 2012-09-03T10:18:07.083 回答
-1
"//Report/Tablix6/RowGroup_Collection/RowGroup/@Cost"

我可能会弄错,但我认为如果 XPath 表达式以双斜杠“//”开头会更好

于 2012-09-03T10:15:47.760 回答