如何恢复XML标签中的所有XML元素?

问题描述:

这是我的XML的一个样本:如何恢复XML标签中的所有XML元素?

 <Library> 
      <Stack> 
       <Book> 
        <Author>....</Author> 
        <Date>....</Date> 
       </Book> 
       <Book> 
        <Author>....</Author> 
        <Date>....</Date> 
       </Book> 
      </Stack> 
      <Stack> 
       <SectionScience> 
        <Book> 
         <Author>....</Author> 
         <Date>....</Date> 
        </Book> 
       </SectionScience> 
       <SectionHorror> 
        <Book> 
         <Author>....</Author> 
         <Date>....</Date> 
        </Book> 
       </SectionHorror> 
       <Book> 
        <Author>....</Author> 
        <Date>....</Date> 
       </Book> 
      </Stack> 
     </Library> 

我已经尝试实现一个恢复所有这些信息的方法,但它不工作:它恢复在Stack只有一个项目,我想它恢复堆栈中的所有元素。

我所得到的是这样的:

堆栈1:第一本书;

堆栈2:第一部分

这是我的代码:

private void ConstructionInterface() 
{ 
    XElement docX = XElement.Load(Application.StartupPath + @"\Library.xml"); 
    foreach (XElement elemColone in docX.Descendants("Stack")) 
    { 
     if (elemColone.Element("SectionHorror") != null) 
     CreateSectionHorror(elemColone.Element("SectionHorror")); 
     else if (elemColone.Element("SectionScience") != null) 
     CreateSectionScience(elemColone.Element("SectionScience")); 
     else if (elemColone.Elements("Book") != null) 
     CreateBook(elemColone.Element("Book")); 
     } 
    } 
+0

找到使用xpath查询xml的很好教程。 – Muckeypuck

+1

我注意到的第一件事是,这是无效的XML(标签中不能有空格)。我注意到的第二件事是,你写的代码只能对每个Stack标签执行一个动作。 – AakashM

+0

是的,我明白,但我不知道如何实现一个algaorythm谁不执行堆栈标记一个动作 –

您需要通过每个Stack的迭代的孩子们:

foreach (XElement elemColone in docX.Descendants("Stack")) 
{ 
    foreach (var sectionOrBook in elemColone.Elements()) 
    { 
     if (sectionOrBook.Name == "SectionHorror") 
      CreateSectionHorror(sectionOrBook); 
     else if (sectionOrBook.Name == "SectionScience") 
      CreateSectionScience(sectionOrBook); 
     else if (sectionOrBook.Name == "Book") 
      CreateBook(sectionOrBook); 
    } 
} 

目前还不清楚什么“恢复”意味着,但如果它意味着创建现有的XML的副本,然后在VB中使用XElement将是

Dim xe As XElement 
    'to load from a file 
    ' xe = XElement.Load("Your Path Here") 

    ' for testing 
    xe = 
     <Library> 
      <Stack> 
       <Book> 
        <Author>....</Author> 
        <Date>....</Date> 
       </Book> 
       <Book> 
        <Author>....</Author> 
        <Date>....</Date> 
       </Book> 
      </Stack> 
      <Stack> 
       <SectionScience> 
        <Book> 
         <Author>....</Author> 
         <Date>....</Date> 
        </Book> 
       </SectionScience> 
       <SectionHorror> 
        <Book> 
         <Author>....</Author> 
         <Date>....</Date> 
        </Book> 
       </SectionHorror> 
       <Book> 
        <Author>....</Author> 
        <Date>....</Date> 
       </Book> 
      </Stack> 
     </Library> 

    Dim recover As XElement = New XElement(xe) ' this line creates a copy 

    ' recover.Save("path here")