这是我的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 :(得分:2)
您还需要遍历每个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);
}
}
答案 1 :(得分:0)
目前还不清楚“恢复”意味着什么,但如果它意味着创建现有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")