我有一个类似于以下内容的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
正确的方法是什么?我应该使用不同的库吗? 谢谢!
答案 0 :(得分:0)
尝试以下:
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();
}
}
}
答案 1 :(得分:0)
您应该自己将$(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)));