1

嘿,我很难“重建”(阅读)我的对象。我的结构很简单:

groupName<--object  
name<--prop  
addres<--prop  
phone<--prop  

我怎样才能将它重建回相同的结构?

这是我将其写入 xml 的方式

 public override void Save(PhoneBook pb)
{
    using (XmlWriter writer = XmlWriter.Create(path))
    {
        writer.WriteStartDocument();
        writer.WriteStartElement("Group");

        foreach (PhoneBookGroup group in pb.Items)
        {
            writer.WriteStartElement("GroupName");

            writer.WriteElementString("GroupName", group.GroupName.ToString());
            foreach (Contect contect in group.Items)
            {
                writer.WriteStartElement("Addres", contect.Addres.ToString());
                writer.WriteStartElement("Number", contect.Number.ToString());
                writer.WriteStartElement("Name", contect.Name.ToString());
            }

            writer.WriteEndElement();
        }

        writer.WriteEndElement();
        writer.WriteEndDocument();
    }
}
4

2 回答 2

1

使用XmlSerializer, 当然对于第一个版本,因为它对代码来说是微不足道的。如果您的老板在看到序列化版本更简单且不易出错之后想要它不同,您应该尝试说服他否则 - 工作的一部分不仅仅是按照您所说的去做,而是至少提供诚实的建议。除非这应该是一次学习经历,否则你的老板是的——这很好也很正常,但你至少应该在按照他说的做之前尽量节省时间和金钱。他可能只是不知道其他选择。

您的代码示例存在错误这一事实突出了手动方法的问题- 您可能是指writer.WriteElementString("Number",...而不是WriteStartElement("Number",.... 使用更结构化的方法更安全、更简单。

如果您确实需要阅读原始 xml,我建议您使用XDocument而不是XmlReader阅读您的文档和 linq to xml 以提取相关位。这仍然比 更简单XmlReader,同时保留了手写代码的全部灵活性(只是慢了一点)。如果您坚持XmlReader解决方案(请注意,这没有技术原因),那么您应该先尝试编写自己的解决方案 - 将您的尝试包含在您的问题中,以便我们可以看到您尝试了什么。

于 2013-02-11T11:05:51.857 回答
1

在查看了您的 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;
}
于 2013-02-11T12:52:50.687 回答