在查看了您的 xml 输出后,我会认真考虑更改您的架构,因为您的 Save 函数的输出会创建结构非常奇怪的 xml,我认为这是您努力重建它的原因。当前输出看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<Group>
<GroupName>
<GroupName>groupName</GroupName>
<Addres xmlns="addy">
<Number xmlns="0123456789">
<Name xmlns="Henry">
<Addres xmlns="address2">
<Number xmlns="9876543210">
<Name xmlns="Dave" />
<GroupName>
<GroupName>secondGroup</GroupName>
<Addres xmlns="fleet">
<Number xmlns="0123456789">
<Name xmlns="Me" />
</Number>
</Addres>
</GroupName>
</Number>
</Addres>
</Name>
</Number>
</Addres>
</GroupName>
</Group>
话虽如此,生成的 xml 不是不可处理的,可以使用下面的方法读回对象。我从您的 Save 代码中唯一假设的是,有某种方法可以从字符串获取 GroupName 对象(因为您使用 ToString 方法将值获取到 xml 中)。在我的测试中,我使用隐式转换运算符实现了该对象,如下所示。
class GroupName
{
public string Name { get; set; }
public override string ToString()
{
return this.Name;
}
// Specific conversion from string to GroupName object
public static implicit operator GroupName(string s)
{
return new GroupName() { Name = s };
}
}
public PhoneBook Rebuild()
{
using (XmlReader reader = XmlReader.Create(path))
{
// read to the start of the xml
reader.MoveToContent();
// create the return object
PhoneBook returnObject = new PhoneBook();
returnObject.Items = new List<PhoneBookGroup>();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
// read each GroupName Node as a separate node collection
if (reader.Name == "GroupName")
{
// This is the root node of the groups
PhoneBookGroup grp = null;
Contact currentContact = null;
// loop the reader from this starting node
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "GroupName":
if (grp == null)
{
grp = new PhoneBookGroup();
returnObject.Items.Add(grp);
// must implement an implicit operator between string and GroupName object
grp.Name = (GroupName)reader.ReadElementString();
}
else
{
// start of a new group, so null what we have so far and start again
grp = null;
}
break;
case "Addres":
// Address is the start node for a contact so create a new contact and start filling it
currentContact = new Contact();
if (grp.Items == null)
{
grp.Items = new List<Contact>();
}
grp.Items.Add(currentContact);
// due to the way the xml is being written the value is held as the namespace !!!
currentContact.Address = reader.NamespaceURI;
break;
case "Number":
// due to the way the xml is being written the value is held as the namespace !!!
currentContact.Phone = reader.NamespaceURI;
break;
case "Name":
// due to the way the xml is being written the value is held as the namespace !!!
currentContact.Name = reader.NamespaceURI;
break;
default:
break;
}
}
}
}
}
}
return returnObject;
}