如何从XML字符串中检索查询参数和命名值

时间:2014-06-20 11:24:55

标签: c# xml regex parsing

我将如何解析以下内容,它至少不会更改该行的布局。所以我需要能够得到Query Parmeter值,即TypeProjectionId以及Name =?的值。有没有人有任何想法?

我使用它来从xml文件中获取文本。

                string path = "/View/Data/ItemsSource";
                XmlNodeList nodeList = currentDocument.SelectNodes(path);
                IDictionary<string, string> keyValuePairList = new Dictionary<string, string>();
                string itemsource;
                itemsource = "";
                foreach (XmlNode node in nodeList)
                {

                    itemsource = node.InnerXml;
                     //   keyValuePairList.Add(new KeyValuePair<string, string>(node.Attributes[0].Value, node.Attributes[0].Value));

                }

itemsource的结果

    <AdvancedListSupportClass xmlns=\"clr-namespace:Microsoft.EnterpriseManagement.UI.ViewFramework;assembly=Microsoft.EnterpriseManagement.UI.ViewFramework\" xmlns:av=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:s=\"clr-namespace:System;assembly=mscorlib\" DataTypeName=\"\" AdapterName=\"viewframework://Adapters/AdvancedList\" FullUpdateAdapter=\"dataportal:EnterpriseManagementObjectProjectionAdapter\" DataSource=\"mom:ManagementGroup\" IsRecurring=\"True\" RecurrenceFrequency=\"{x:Static s:Int32.MaxValue}\" FullUpdateFrequency=\"1\" Streaming=\"true\">
      <AdvancedListSupportClass.Parameters>
        <QueryParameter Parameter=\"TypeProjectionId\" Value=\"$MPElement[Name='System.WorkItem.Incident.View.ProjectionType']$\" />
      </AdvancedListSupportClass.Parameters>
    </AdvancedListSupportClass> 

1 个答案:

答案 0 :(得分:0)

您的XML具有默认命名空间,因此您需要使用XmlNamespaceManager才能使用XPath查询XML。例如,要获取Parameter属性的值,您可以执行以下操作:

XmlNamespaceManager nsManager = new XmlNamespaceManager(new NameTable());

//register ns prefix to point to default namespace 
nsManager.AddNamespace("ns", node.FirstChild.GetNamespaceOfPrefix(""));

//use the namespace manager and registered prefix to get desired element
string xpath = "/ns:AdvancedListSupportClass/ns:AdvancedListSupportClass.Parameters/ns:QueryParameter";
var queryParameters = node.SelectNodes(xpath, nsManager);

foreach(XmlNode queryParameter in queryParameters)
{
    //get value of Parameter attribute of each <QueryParameter>
    Console.WriteLine(queryParameter.Attributes["Parameter"].Value);
}