0

使用できる任意の方法を使用して、vcxprojファイルを解析しようとしています(XPathDocument、XElement、XDocumentを試しました...何も機能しません)

典型的なプロジェクト構成:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="P">  ...  </ItemGroup>
  <ItemGroup>   <C I="..." />    </ItemGroup>
  <ItemGroup>   <C I="..." />    </ItemGroup>
  <ItemGroup>    ...  </ItemGroup>    
  <Import Project="aaaaa" />
  <PropertyGroup C="..." Label="...">  ... </PropertyGroup>  
  <Import Project="ooother" />
  <ImportGroup Label="E">  </ImportGroup>
  <ImportGroup Label="I_NEED_THIS" C="...">
    <Import Project="other" Condition="x" Label="L" />
    <Import Project="I_NEED_THIS_VALUE" />
  </ImportGroup>  
  <Import Project="bbbbb" />
  <ImportGroup Label="Ex">  </ImportGroup>
</Project>

ラベル I_NEED_THIS を使用して ImportGroup 内からアイテムを取得しようとしています。それらをすべて取得して、(もしあれば)ラベルまたは条件を確認できるようにしたいと考えています...

似たような名前の要素が複数あるのが問題なのではないかと思ったので、一度に1つのレベルだけを取得しようとしましたが、

XElement xmlTree = XElement.Load(projectPath);
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
List<XElement> projectElements = (
    from mainElement in xmlTree.Descendants(ns + "Project")
    from subElement in mainElement.Elements()
    select subElement
).ToList();

if (projectElements.Count == 0)
  MessageBox.Show("Nothing is working today");

上記の後に、いくつかの foreach ループが続きます...

foreach (XElement projectElement in projectElements)
{
List<XElement> importElements = (
   from mainElement in projectElement.Descendants(ns + "ImportGroup")
   from subElement in mainElement.Elements()
   select subElement
).ToList();
...
}

等々ですが、最初のループまでテストしたらprojectElementsのCountが0になってしまいました…

名前空間なしでも試してみました...

何が欠けていますか?ありがとうございました...

4

1 に答える 1

1

へのこれらの呼び出しを取り除くことができますDescendants。直接電話Elementsしても問題ないはずです。これは、単純なループを使用してこれを実現する方法です。

// we can directly grab the namespace, it's better than hard-coding it
XNamespace ns = xmlTree.Name.Namespace;
// xmlTree itself is the Project element, just to make sure:
Debug.Assert(xmlTree.Name.LocalName == "Project");

// the following is all elements named "ImportGroup" under "Project"
var importGroups = xmlTree.Elements(ns + "ImportGroup");
foreach(XElement child in importGroups)
{
    // the following are all "Import" elements under "ImportGroup" elements
    var imports = child.Elements(ns + "Import");
    foreach (var importElem in imports)
    {
        Console.WriteLine(importElem.Attribute("Project").Value);
    }
}

//This is the output:
//other
//I_NEED_THIS_VALUE

または、属性 valued を含む 2 番目の要素に直接移動する次のコードを使用することもできます"I_NEED_THIS_VALUE"

var elems = xmlTree.Elements(ns + "ImportGroup")
    .Where(x => x.Attributes("Label").Any(xattr => xattr.Value == "I_NEED_THIS"))
        .Elements(ns + "Import")
        .Where(x => x.Attributes("Project").Any(xattr => xattr.Value == "I_NEED_THIS_VALUE"));
于 2012-11-13T05:02:41.090 に答える