我想从XLM文件中获取带有Xpath的节点列表。我想通过搜索某个属性来获取它们。这是Xml文件。
<ItemGroup>
<Compile Include="Algorithmus_Müllabfuhr\Algorithm.cs" />
<Compile Include="Algorithmus_Müllabfuhr\Tests\AlgorithmTest.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
我的输出应该是
Algorithmus_Müllabfuhr\ Algorithm.cs
Algorithmus_Müllabfuhr\测试\ AlgorithmTest.cs
Form1.cs的
Form1.Designer.cs
Program.cs的
属性\ AssemblyInfo.cs中
Form1.resx中
属性\ Resources.resx
属性\ Resources.Designer.cs
packages.config
属性\ Settings.settings
属性\ Settings.Designer.c
到目前为止,我只搜索带有“Compile”元素的节点。并获得价值。现在我需要从具有属性“Include”的节点获取所有值。
var doc = new XmlDocument();
doc.Load(csproj.FullName);
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("msbld", "http://schemas.microsoft.com/msbuild/2003");
XmlNodeList xnList = doc.SelectNodes(@"/msbld:Project/msbld:ItemGroup/msbld:Compile", ns);
foreach (XmlNode node in xnList)
{
referencedfiles.Add(new FileInfo(Path.Combine(csproj.Directory.FullName, node.Attributes["Include"].Value)));
}
CompareLists(filesinfiles, referencedfiles);
Stackoverflow select all xml nodes which contain a certain attribute 我看了这个帖子,它似乎对我不起作用。我也遇到了XML文档中命名空间的问题。
答案 0 :(得分:0)
解决此问题的另一种方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Test {
class Program {
public static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("PATHTOXMLFILE");
List<string> result = RetrieveValues(doc, "Include");
foreach(string item in result)
{
Console.WriteLine(item);
}
Console.Read();
}
public static List<string> RetrieveValues(XmlDocument doc, string attributeName)
{
var list = new List<string>();
string xpath = @"//*[@" + attributeName + "]";
XmlNodeList xmlNodeList = doc.SelectNodes(xpath);
foreach (XmlNode xmlNode in xmlNodeList)
{
list.Add(xmlNode.Attributes[attributeName].InnerText);
}
return list;
}
}
}
希望这有帮助!