2017-07-14 7 views
-1

私が次のものに似たものとしてXMLファイルを持っている:私はC#(XElementオブジェクトとXDocumentを使用して)で、この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> 

は今、私は$(プロパティ1)を展開する必要があり、最終的なように

C:\ DummyProperty \ DummyFile.txt

が、私はこれを達成し、

を取得し続けることができません私はこのパスのために取得する文字列です

C:\ $(プロパティ1)\ DummyFile.txt

正しい方法は何ですか?私が使用すべき別のライブラリがありますか? ありがとうございました!次

+0

'csproj'ファイルを解析するためのMicrosoft.Build.dll –

答えて

0

試してください:あなたは自分でDummyProperty$(Property1)の交換をすべき

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

。あなたがから[ProjectRootElement](https://msdn.microsoft.com/en-us/library/microsoft.build.construction.projectrootelement(V = vs.140).aspxの)クラスを使用しようとすることができ

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))); 
関連する問題