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 内部获取项目,我想获取所有项目并能够检查(如果有)它们的标签或条件......

我怀疑问题可能是有多个名称相似的元素,所以我尝试一次只获取一个级别,

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 的计数为 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

或者,您可以使用以下代码,直接转到包含属性 value 的第二个元素"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 回答