【问题标题】:How to expand Property references in XML Document C#?如何在 XML 文档 C# 中扩展属性引用?
【发布时间】:2017-07-14 15:03:45
【问题描述】:

我有一个类似于以下内容的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" 
xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="14.0">
    <PropertyGroup>
       <Property1>DummyProperty</Property1>
       </PropertyGroup>
    <Reference>
       <HintPath>C:\$(Property1)\DummyFile.txt</HintPath>
    </Reference>
</Project>

现在,当我尝试在 C# 中解析这个 XML(使用 XElement 和 XDocument)时,我需要扩展 $(Property1) 以便我为这个路径得到的最终字符串是:

C:\DummyProperty\DummyFile.txt

但我无法做到这一点并继续获得

C:\$(Property1)\DummyFile.txt

什么是正确的方法?我应该使用不同的库吗? 谢谢!

【问题讨论】:

  • 您可以尝试使用 Microsoft.Build.dll 中的ProjectRootElement 类来解析csproj 文件。

标签: c# xml xml-parsing


【解决方案1】:

尝试以下:

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);
            XElement project = doc.Root;
            XNamespace ns = project.GetDefaultNamespace();

            string property1 = (string)project.Descendants(ns + "Property1").FirstOrDefault();
            string hintPath = (string)project.Descendants(ns + "HintPath").FirstOrDefault();

        }
    }
}

【讨论】:

    【解决方案2】:

    您应该自己将$(Property1) 替换为DummyProperty

    var doc = XDocument.Load(pathToTheProjectFile);
    var ns = doc.Root.GetDefaultNamespace();
    
    var properties = doc.Descendants(ns + "PropertyGroup")
                        .SelectMany(property => property.Elements())
                        .Select(element => new 
                        { 
                            Old = $"$({element.Name.LocalName})", 
                            New = element.Value 
                        });
    
    var hintPathCollection = 
        doc.Descendants(ns + "HintPath")
           .Select(element => properties.Aggregate(element.Value, 
                                                   (path, values) => path.Replace(values.Old, values.New)));
    

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2020-03-28
      • 2010-09-18
      • 2021-03-11
      相关资源
      最近更新 更多