使用C#从XML文件中获取价值

时间:2015-08-19 06:16:59

标签: c# xml

我想从下面的XML文件中仅获取'Param1'。请帮助。我的代码它给了我SSIS参数节点下所有属性的完整字符串值,但是t没有给出Param1。

XML文件内容:`

<?xml version="1.0"?>
<SSIS:Parameters xmlns:SSIS="www.microsoft.com/SqlServer/SSIS">
  <SSIS:Parameter
    SSIS:Name="param1">
    <SSIS:Properties>
      <SSIS:Property
        SSIS:Name="ID">{6fc5a81b-723b-4821-b948-0cbd44d86c84}</SSIS:Property>
      <SSIS:Property
        SSIS:Name="CreationName"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="Description"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="IncludeInDebugDump">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Required">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Sensitive">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Value"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="DataType">18</SSIS:Property>
    </SSIS:Properties>
  </SSIS:Parameter>
</SSIS:Parameters>

`

我的代码片段:

 XmlDataDocument xmldoc = new XmlDataDocument();
        XmlNodeList xmlnode;
        int i = 0;
        string str = null;
        FileStream fs = new FileStream(@"D:\Sample SSIS\sampleDeploymentDemo\sampleDeploymentDemo\Project.params", FileMode.Open, FileAccess.Read);
        xmldoc.Load(fs);
        xmlnode = xmldoc.GetElementsByTagName("SSIS:Parameters");
        for (i = 0; i <= xmlnode.Count - 1; i++)
        {
            xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
            str = xmlnode[i].InnerText.Trim() + "  " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + "  " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
            Console.WriteLine(str);
        }
        Console.ReadLine();

2 个答案:

答案 0 :(得分:0)

&#34;参数1&#34;是属性。您可以使用以下代码获取它:

        ...
        xmlnode = xmldoc.GetElementsByTagName("SSIS:Parameters");

        for (i = 0; i <= xmlnode.Count - 1; i++)
        {
           var val = xmlnode[i].FirstChild.Attributes["SSIS:Name"].Value;
           Console.WriteLine(val);
        }
        Console.ReadLine();
        ...

请参阅this link

答案 1 :(得分:0)

尝试XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            var results = doc.Descendants().Where(x => x.Name.LocalName == "Parameter").Descendants().Where(y => y.Name.LocalName == "Property").Select(z => new
            {
                value = z.Attributes().Where(a => a.Name.LocalName == "Name").Select(b => b.Value).FirstOrDefault()
            }).ToList();
            foreach (var item in results)
            {
                Console.WriteLine(item.value);
            }

        }
    }
}
​