2017-07-14 64 views
-1

我有一個XML文件類似於如下的內容:如何展開XML文檔C#中的屬性引用?

<?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> 

現在,當我嘗試解析這個XML中(使用的XElement和的XDocument)C#,我需要擴大$(Property1),使最終字符串,我得到這個路徑是:

C:\ DummyProperty \ DummyFile.txt

,但我無法做到這一點,並繼續得到

C:\ $(Property1)\ DummyFile.txt

什麼是正確的方法是什麼?我應該使用不同的圖書館嗎? 謝謝!

+0

你可以嘗試使用[ProjectRootElement(https://msdn.microsoft.com/en-us/library/microsoft.build.construction.projectrootelement(V = vs.140)的.aspx)從類用於解析'csproj'文件的Microsoft.Build.dll。 –

回答

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(); 

     } 
    } 
} 
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)));