使用Linq to XML而不是XML Reader / Writer

时间:2013-10-30 21:51:17

标签: c# .net xml linq linq-to-xml

我正在尝试创建一个简单的工具来解析xml文件,如果/当找到某个元素时它获取值然后使用该值执行代码然后执行的代码输出一个新值然后被替换并保存一个新的XML文件。事实证明,这似乎更加困难。

目前我正在使用XML阅读器和XML编写器的组合。这是非常冗长的,我似乎有小问题,这是难以修复的方式。 You can see an example of my previous approach and it's code here.

我想知道是否有人可以帮我弄清楚如何使用Linq to XML来完成这项工作。我需要筛选原始文档的XML,查找“ClInclude”和“ClCompile”,当找到它们时,我需要执行代码并用新值替换这些属性字符串。 For a better example of what I am accomplishing, you can check the post prior to the last.

我做了很多尝试,并决定放弃读者/作者。任何人都可以帮我完成这个吗?以下是我在Linq to XML中所做的一次尝试:

                string baseDir = (textBox2.Text + "\\" + safeFileName);
                string vcName = Path.GetFileName(textBox1.Text);
                string vcProj = Path.Combine(baseDir, vcName);

                XDocument xmlDoc = XDocument.Load(textBox1.Text);

                var items = from item in xmlDoc.Elements()
                            select item;

                foreach (XElement itemElement in items)
                {
                    if (itemElement.Name == "ClInclude")
                    {
                        // itemElement.SetElementValue("Include", "include/");
                        textBox3.AppendText(itemElement.Value);
                    }

                }

                xmlDoc.Save(vcProj);

现在我只是将它们附加到文本框中,只是为了测试它。我似乎无法通过Clinclude或ClCompile带回任何元素。以下是我尝试获取和替换值的行的示例:

<ClCompile Include="..\..\lib\projx\conf.c" />
    <ClCompile Include="..\..\lib\projx\hash.c" />
    <ClCompile Include="..\..\lib\projx\init.c" />

以下是我正在解析的XML的完整示例:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <ProjectGuid>{57900E99-A405-49F4-83B2-0254117D041B}</ProjectGuid>
    <Keyword>Win32Proj</Keyword>
    <RootNamespace>libprojx</RootNamespace>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    <ConfigurationType>DynamicLibrary</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <CharacterSet>MultiByte</CharacterSet>
    <PlatformToolset>v110</PlatformToolset>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    <ConfigurationType>DynamicLibrary</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>MultiByte</CharacterSet>
    <PlatformToolset>v110</PlatformToolset>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <ClCompile>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <Optimization>MaxSpeed</Optimization>
      <PreprocessorDefinitions>WIN32;projx_EXPORTS;_DEBUG;_WINDOWS;_USRDLL;LIBprojx_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <AdditionalIncludeDirectories>..\..\Win32;..\..\lib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <BasicRuntimeChecks>Default</BasicRuntimeChecks>
      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
    </ClCompile>
    <Link>
      <SubSystem>Windows</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <AdditionalLibraryDirectories>..\..\..\..\Debug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
      <AdditionalDependencies>libdirect.lib;%(AdditionalDependencies)</AdditionalDependencies>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>WIN32;projx_EXPORTS;NDEBUG;_WINDOWS;_USRDLL;LIBprojx_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <AdditionalIncludeDirectories>..\..\Win32;..\..\lib;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
    </ClCompile>
    <Link>
      <SubSystem>Windows</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
      <AdditionalLibraryDirectories>..\..\..\..\Debug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
      <AdditionalDependencies>libdirect.lib;%(AdditionalDependencies)</AdditionalDependencies>
    </Link>
  </ItemDefinitionGroup>
  <ItemGroup>
    <ClCompile Include="..\..\lib\projx\conf.c" />
    <ClCompile Include="..\..\lib\projx\hash.c" />
    <ClCompile Include="..\..\lib\projx\init.c" />
    <ClCompile Include="..\..\lib\projx\shmalloc.c" />
    <ClCompile Include="..\..\lib\projx\shm\fake.c" />
    <ClCompile Include="..\..\lib\projx\vector.c" />
    <ClCompile Include="dllmain.c" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="..\..\lib\projx\conf.h" />
    <ClInclude Include="..\..\lib\projx\hash.h" />
    <ClInclude Include="..\..\lib\projx\shmalloc.h" />
    <ClInclude Include="..\..\lib\projx\types.h" />
    <ClInclude Include="..\..\lib\projx\vector.h" />
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>

1 个答案:

答案 0 :(得分:1)

首先,您需要找到您的ClInclude,正如我所理解的那样:var includs = xdoc.Descendants("ClInclude")将为您提供所有ClInclude。如果您需要具有一些特殊Include属性值的特定ClInclude,您可以这样做:

var specificInclude = xdoc.Descendants("ClInclude")
      .Where(inc => inc.Attribute("Include").Value == yourValue).FirstOrDefault();

接下来,您需要将Include属性值替换为新的属性值,如下所示:

specificInclude.Attribute("Include").Value = newValue;

控制台应用的完整示例:

string xml = @"<root><ItemGroup><ClInclude id=""1""></ClInclude><ClInclude id=""2""></ClInclude></ItemGroup></root>";

var newxDoc = XDocument.Parse(xml);

Console.WriteLine("Before");
Console.WriteLine(newxDoc.ToString());

var s = newxDoc.Descendants("ClInclude").Where(b => b.Attribute("id").Value == "2").FirstOrDefault();
s.Attribute("id").Value = "3";

Console.WriteLine("After");
Console.WriteLine(newxDoc.ToString());
Console.ReadLine();

希望有所帮助!