如何从XDocument.Root中降低一级?

时间:2014-07-09 01:03:26

标签: c# xml linq linq-to-xml

例如,从root(PBC)我想要返回一个级别(PBCVersion,ProjectName,ProjectVersion,Targets,Packages),而是使用:

foreach (XElement x in oPbcXDocument.Root.Elements())
{
    Console.WriteLine(x.Value);
}

我回来了:

PBC
1
dfcs
1102
RCM565bas_build.bat RCM565scm-00110binlogWINSIMbas_build.bat SIMscm-00110binlog
bas_package.batscm-00110PackageoutlogDFCS1102RCM565LastSuccessfulComponentsDFCS1102WINSIMLastSuccessfulComponents2

这是XML:

<?xml version="1.0" encoding="utf-8"?>
<PBC>
  <PBCVersion>1</PBCVersion>
  <ProjectName>dfcs</ProjectName>
  <ProjectVersion>1102</ProjectVersion>
  <Targets>
    <Target>
      <TargetName>RCM565</TargetName>
      <CommandLine>bas_build.bat RCM565</CommandLine>
      <BuildEnvTypeName>scm-00110</BuildEnvTypeName>
      <RelativeOutputPath>bin</RelativeOutputPath>
      <RelativeLogPath>log</RelativeLogPath>
      <Dependencies/>
    </Target>
    <Target>
      <TargetName>WINSIM</TargetName>
      <CommandLine>bas_build.bat SIM</CommandLine>
      <BuildEnvTypeName>scm-00110</BuildEnvTypeName>
      <RelativeOutputPath>bin</RelativeOutputPath>
      <RelativeLogPath>log</RelativeLogPath>
      <Dependencies/>
    </Target>
  </Targets>
  <Packages>
    <Package>
      <CommandLine>bas_package.bat</CommandLine> 
      <BuildEnvTypeName>scm-00110</BuildEnvTypeName> 
      <PackageName>Package</PackageName> 
      <RelativeOutputPath>out</RelativeOutputPath> 
      <RelativeLogPath>log</RelativeLogPath> 
      <Dependencies>
        <BuildDependency>
          <ProjectName>DFCS</ProjectName>
          <ProjectVersion>1102</ProjectVersion>
          <TargetName>RCM565</TargetName>
          <ProjectBuild>LastSuccessful</ProjectBuild> 
          <RelativeSandboxPath>Components</RelativeSandboxPath> 
        </BuildDependency>
        <BuildDependency>
          <ProjectName>DFCS</ProjectName>
          <ProjectVersion>1102</ProjectVersion>
          <TargetName>WINSIM</TargetName>
          <ProjectBuild>LastSuccessful</ProjectBuild> 
          <RelativeSandboxPath>Components2</RelativeSandboxPath> 
        </BuildDependency>
      </Dependencies>
    </Package>
  </Packages>
</PBC>

我怎样才能只返回一个级别?

2 个答案:

答案 0 :(得分:2)

您的代码是正确的,以便将所有元素都放在Root的一个级别,但不清楚您希望获得哪种输出。我假设您希望获得上述元素的完整标记:

foreach (XElement x in oPbcXDocument.Root.Elements()) 
{ 
    Console.WriteLine(x.ToString()); 
}

答案 1 :(得分:0)

不要使用Value属性,因为它始终包含所有后代的文本表示。根据需要处理元素。