读取XML文件时仅获取Group元素文本的最后一个元素



我试图读取一个XML文件,但当我读取它时,它只会获取我的Group元素的最后一个值,而不是在每个Group的结束符处设置Group的文本属性。感谢所有的帮助。

public static void ReadFile()
{
    string MyText = string.Empty;
    string Notes = string.Empty;
    string UserName = string.Empty;
    string Password = string.Empty;
    string Url = string.Empty;
    string Title = string.Empty;
    string MyGroup = string.Empty;
    Group group = new Group("Hello", 0);
    XmlTextReader xmlReader = new XmlTextReader("C:/KeyText.xml");
    while (xmlReader.Read()) // Read nodes sequentially
    {
        if (xmlReader.Name == "Group" & xmlReader.NodeType.ToString() == "EndElement")
        {
            group.Text = MyText;
            AddGroupXML(group);
        }
        if (xmlReader.NodeType == XmlNodeType.Element)
        {
            if (xmlReader.LocalName == "Text")
            {
                MyText = xmlReader.ReadString();
            }
            if (xmlReader.LocalName == "Notes")
            {
                Notes = xmlReader.ReadString();
            }
            if (xmlReader.LocalName == "UserName")
            {
                UserName = xmlReader.ReadString();
            }
            if (xmlReader.LocalName == "Password")
            {
                Password = xmlReader.ReadString();
            }
            if (xmlReader.LocalName == "Url")
            {
                Url = xmlReader.ReadString();
            }
            if (xmlReader.LocalName == "Title")
            {
                Title = xmlReader.ReadString();
            }
        }
        if (xmlReader.Name == "Key" & xmlReader.NodeType.ToString() == "EndElement")
        {
            Key MyKey = new Key();
            MyKey.Notes = Notes;
            MyKey.Title = Title;
            MyKey.UserName = UserName;
            MyKey.Url = Url;
            MyKey.Password = Password;
            group.Keys.Add(MyKey);
        }
    }
    xmlReader.Close();
    GroupsRead.Invoke();
}

XML:

<?xml version="1.0"?>
<Groups>
  <Group>
    <ImageIndex>0</ImageIndex>
    <Text>wcwpgcuotlx</Text>
    <Keys>
      <Dog/>
      <Key>
        <Notes>4ktaiyduner</Notes>
        <Password>0y2cg1kodre</Password>
        <Title>a2yj4biqd5u</Title>
        <Url>de2uym5vyg1</Url>
        <UserName>ogcl3uyvy2r</UserName>
      </Key>
      <Key>
        <Notes>3dmchyaqcvt</Notes>
        <Password>lbgfralkng4</Password>
        <Title>fnha4ienzua</Title>
        <Url>n3pmk5elaso</Url>
        <UserName>njk55ov4eef</UserName>
      </Key>
    </Keys>
  </Group>
  <Group>
    <ImageIndex>0</ImageIndex>
    <Text>vrmijzokft2</Text>
    <Keys>
      <Dog/>
    </Keys>
  </Group>
</Groups>

我认为您的问题是您有一个用于所有组的Group对象。因此,由于每次都使用相同的参数调用AddGroupXML(),因此结果将多次包含相同的对象。文本值将是您为其设置的最后一个值。

要解决此问题,请更改将组添加到以下内容的代码:

group.Text = MyText;
AddGroupXML(group);
group = new Group("Hello", 0);

将来,如果使用LINQ to XML来处理XML,可能会更容易。如果使用它,您的代码会简单得多。(这种方法的缺点是它将整个XML加载到内存中,这对于巨大的XML文件来说是个坏主意。)

最新更新