2011-04-08 73 views
0

我在使用XmlReader讀取XML中某個元素的屬性時遇到了一些麻煩。爲了讓函數透視,我有一個組合框讀取文件夾中的所有xml文件。然後將第一個組合框中選擇的項目用作XmlReader的輸入。將XML屬性讀入組合框

array<String^>^ HashMe::PopulateTCList() 
{ 
    int SelectedFileNum = comboBox1->SelectedIndex; 
    array<String^>^ Files = PopulateProjectList(); 

    array<String^>^ AllTC = gcnew array<String^>(100); 
    int number = Files->GetLength(0); 

    try 
    { 
     int x = 0; 

     for(int y = 0; y < number; y++) 
     { 
      String^ File = Files[y]; 

      if(SelectedFileNum == x) 
      {   
       XmlReader^ Reader = XmlReader::Create(File); 

       while(Reader->Read()) 
       { 
        if((Reader->NodeType == XmlNodeType::Element) && (Reader->Name == "TestCycle")) 
        { 
         String^ TCNumber = Reader->ReadElementContentAsString(); 
         comboBox2->Items->Add(TCNumber); 
        } 
        else 
        { 
         Reader->ReadToFollowing("TestCycle"); 
        } 
       } 
      } 
      x = x +1; 
     } 
    } 
    catch (Exception^ e) 
    { 
     MessageBox::Show(e->ToString()); 
    } 
return AllTC; 
} 

的XML佈局類似於下面的一個:

<?xml version="1.0" encoding="utf-8"?> 
<Project Name="test"> 
    <TestCycle Number="1"> 
    <Files> 
     <FileName File="C:\Users\brandonm\Documents\asd.xps" /> 
     <HashCode Code="AB-B5-85-EC-FE-C4-E2-41-09-6A-A8-77-69-A9-8D-1F" /> 
    </Files> 
    </TestCycle> 
    <Project Name="test"> 
    <TestCycle Number="2"> 
     <Files> 
     <FileName FileName="C:\Users\brandonm\Documents\asd.xps" /> 
     <HashCode HashCode="AB-B5-85-EC-FE-C4-E2-41-09-6A-A8-77-69-A9-8D-1F" /> 
     </Files> 
    </TestCycle> 
    </Project> 
    <Project Name="test"> 
    <TestCycle Number="3"> 
     <Files> 
     <FileName FileName="C:\Users\brandonm\Documents\asd.xps" /> 
     <HashCode HashCode="AB-B5-85-EC-FE-C4-E2-41-09-6A-A8-77-69-A9-8D-1F" /> 
     </Files> 
    </TestCycle> 
    </Project> 
</Project> 

基本上我需要從每個TestCycle元件的數量在組合框來顯示。

如果任何人有一個建議或知道我的語法有什麼錯誤,請讓我知道。我無法在網上找到一個可靠的例子。

回答

0

我不知道你要找正是對,但這裏是返回一個包含所有在給定的XML文件中的TestCycleNumber屬性的array<int>^功能:

using namespace System; 

array<int>^ ReadTestCycleNumbers(String^ xmlFileName) 
{ 
    using System::Collections::Generic::List; 
    using namespace System::Xml::XPath; 

    List<int> nums; 
    XPathNavigator^ root = XPathDocument(xmlFileName).CreateNavigator(); 
    for each (XPathNavigator^ nav in root->Select(L"//TestCycle[@Number != '']")) 
     nums.Add(int::Parse(nav->GetAttribute(L"Number", String::Empty))); 
    return nums.ToArray(); 
} 

確保您的項目有一個參考System.Xml.dll

+0

謝謝ildjarn這就是我所需要的。 – Brandonm 2011-04-09 09:04:04