2011-05-14 69 views
2

我想达到X:房产节点及其属性:不能达到特定的XML节点

XML:

<Activity mc:Ignorable="sap" x:Class="WebApplication3.work" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mv="clr-namespace:Microsoft.VisualBasic;assembly=System" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:s1="clr-namespace:System;assembly=System" xmlns:s2="clr-namespace:System;assembly=System.Xml" xmlns:s3="clr-namespace:System;assembly=System.Core" xmlns:s4="clr-namespace:System;assembly=System.ServiceModel" xmlns:sa="clr-namespace:System.Activities;assembly=System.Activities" xmlns:sad="clr-namespace:System.Activities.Debugger;assembly=System.Activities" xmlns:sap="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=System" xmlns:scg1="clr-namespace:System.Collections.Generic;assembly=System.ServiceModel" xmlns:scg2="clr-namespace:System.Collections.Generic;assembly=System.Core" xmlns:scg3="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:sd="clr-namespace:System.Data;assembly=System.Data" xmlns:sl="clr-namespace:System.Linq;assembly=System.Core" xmlns:st="clr-namespace:System.Text;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <x:Members> 
    <x:Property Name="number1" Type="InArgument(x:Int32)" /> 
    <x:Property Name="number2" Type="InArgument(x:Int32)" /> 
    <x:Property Name="total" Type="OutArgument(x:Int32)" /> 
    </x:Members> 
....... 
</Activity> 

C#代码:

 XmlDocument doc = new XmlDocument(); 
     doc.Load(filePath); 

     XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); 
     manager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml"); 
     XmlNodeList elements = doc.SelectNodes("//Activity/x:Members/x:Property",manager); 

不幸的是元素变量的回报有0个节点。你可以帮我吗?

+0

你不应该选择' (“/ Activity/x:Members”)'节点,然后查找它的ChildNodes? – Marco 2011-05-14 20:16:33

+0

看起来'Activity'元素是用一个名称空间定义的,因此您可能需要将该名称空间添加到管理器并修改您的xpath以匹配它。 – ewh 2011-05-14 20:23:41

+0

有人提供了GetElementsByTagName(“x:Property”);并删除了他的帖子。它的工作原理是这样的,但这会导致问题吗? – ozgkrc 2011-05-14 20:24:06

回答

0

试试这个

XmlNodeList elemList = doc.GetElementsByTagName("x:Property"); 
+0

它这样工作,谢谢 – ozgkrc 2011-05-14 20:24:47

2
var xdocument = XDocument.Load(filePath); 
var xname = XName.Get("Property", "http://schemas.microsoft.com/winfx/2006/xaml"); 
var propertyNodes = xdocument.Descendants(xname).ToList(); 
0

的问题是,该文件是在默认命名空间

在你的XPath表达式:

//Activity/x:Members/x:Property 

名称Activity为前缀的,并与XPath认为是“没有命名空间”。

XPath评估程序正在尝试查找文档中“没有命名空间”中的所有Activity元素并失败 - 因此为0结果。

该解决方案易于

此行只是添加到您的代码:

manager.AddNamespace("def", "http://schemas.microsoft.com/netfx/2009/xaml/activities"); 

然后评估该XPath表达式

XmlNodeList elements = doc.SelectNodes("//def:Activity/x:Members/x:Property",manager);