2009-12-06 2 views
2

이것은 이상한 질문처럼 보일지 모르지만 나는 이것에 대한 내 자신의 이유가 있습니다! 프로젝트의 XML 표현 인 Delphi 2009 프로젝트 파일 (.dproj)을 파싱하려고합니다. 문서를 XmlDocument로로드 할 수 있지만 프로젝트에서 사용되는 단위를 가져 오면 SelectNodes에서 빈 목록을 제공합니다.C#에서 델파이 프로젝트 파일 구문 분석

프로젝트의 예는 다음과 같습니다

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 
... 
... 
<ItemGroup> 
    <DelphiCompile Include="Package.dpk"> 
    <MainSource>MainSource</MainSource> 
    </DelphiCompile> 
    <DCCReference Include="vcl.dcp"/> 
    <DCCReference Include="Unit1.pas"/> 
    <DCCReference Include="Unit2.pas"/> 
    <DCCReference Include="Unit3.pas"/> 
    <DCCReference Include="Unit4.pas"/> 
    <DCCReference Include="Unit5.pas"/> 
    ... 
</ItemGroup> 
</Project> 

코드의 예는 다음과 같습니다

ProjectDocument.Load(FileName); 
    XmlNodeList nodeList; 
    XmlElement RootNode = ProjectDocument.DocumentElement; 

    string xmlns = RootNode.Attributes["xmlns"].Value; 

    // This gives an empty list 
    nodeList = RootNode.SelectNodes("/Project/ItemGroup/DCCReference"); 
    foreach (XmlNode title in nodeList) 
    { 
    Console.WriteLine(title.InnerXml); 
    } 

    // This also gives an empty list 
    nodeList = RootNode.SelectNodes("/ItemGroup/DCCReference"); 
    foreach (XmlNode title in nodeList) 
    { 
    Console.WriteLine(title.InnerXml); 
    } 
내가 누락해야하기 때문에 문제는 정말 어떻게 내가 잘못하고있는 중이 야한다

어떤 것. 유일하게 이상한 점은 문서가 .xml이 아니고 .dproj라는 점입니다.

이렇게 해결해 주시면 미리 감사드립니다.

마크

답변

3

인용 the documentation :

비고

XPath 식 네임 스페이스 해상도를 필요로하는 경우, 당신은 그것의 인수로 XmlNamespaceManager 걸리는 SelectNodes 과부하를 사용해야합니다. XmlNamespaceManager은 네임 스페이스를 확인하는 데 사용됩니다.

XPath 식에 접두사가 포함되어 있지 않은 경우, 네임 스페이스 URI가 빈 공간이라고 가정한다. XML에 기본 네임 스페이스가 포함되어있는 경우에도 XmlNamespaceManager을 사용하고 접두사와 네임 스페이스 URI를 추가해야합니다. 그렇지 않으면 노드를 선택하지 않습니다.

당신은 two-argument version of SelectNodes이 필요합니다. 또한 노드에 내용이 없으므로 InnerXML 속성은 비어 있습니다. 비어 있지 않은 목록을 얻으면 코드는 여전히 빈 줄 목록을 인쇄합니다.

+0

위의 두 가지 답변을 함께 사용하면 큰 도움이됩니다. 감사합니다. – Mmarquee

2

당신은 사용할 필요가 XmlNamespaceManager :

또한
var nsmgr = new XmlNamespaceManager(ProjectDocument.NameTable); 
nsmgr.AddNamespace("x", ProjectDocument.DocumentElement.NamespaceURI); 
var nodes = doc.SelectNodes("descendant::x:DCCReference", nsmgr); 
+0

위의 두 가지 답변을 조합하면 트릭을 만들 수 있습니다. 감사합니다. – Mmarquee

0

, 왜 당신이 당신의 자신의 간단한 파서를 사용하여 DPR 파일을 구문 분석하지 않습니다? 행을 찾은 다음 세미콜론으로 줄을 칠 때까지 그 이후의 모든 행을 가져 와서 주석과 마지막 쉼표를 제거하십시오.

더 간단한 구문 분석 외에 이점 2는 모든 delphi 버전에서 작동하지만 DPROJ 및 이와 동등한 파일은 delphi 버전과 다른 점이 많습니다.