【问题标题】:XmlTextReader ignores second and third Profile elementXmlTextReader 忽略第二个和第三个 Profile 元素
【发布时间】:2011-06-14 20:28:15
【问题描述】:

我有以下 XML 文件:

<?xml version="1.0"?><!--This document contains the profiles that have been created.--><Profiles>
  <Profile>
    <name>One</name>
    <date>Two</date>
  </Profile>
  <Profile>
    <name>One</name>
    <date>Two</date>
  </Profile>
  <Profile>
    <name>One</name>
    <date>Two</date>
  </Profile>
</Profiles>

问题是当我使用 XmlTextReader 时,它只读取第一个配置文件而忽略了第二个和第三个。

    public ArrayList ReadProfiles() {

  ArrayList result = new ArrayList();
  Hashtable currentProfile = null;

  string currentName = "";
  string currentValue = "";  

  XmlTextReader textReader = new XmlTextReader(profilesPath);
  // Read until end of file
        while (textReader.Read()) {
   switch(textReader.NodeType) {

   case XmlNodeType.Text: {
    currentValue = textReader.Value;
    Debug.Log("found text = " + currentValue);
    }
    break;

   case XmlNodeType.Element: {
    currentName = textReader.Name;
    switch(currentName) {

    case "Profiles": 
     Debug.Log("found profiles");
     break;
    case "Profile":
     Debug.Log("found profile");
     break;
    case "name":
     Debug.Log("found name");
     break;
    case "date":
     Debug.Log ("found date");
     break;
    default:
     Debug.Log("default in");
     break;
    }
   }
    break;
   case XmlNodeType.Comment:
    Debug.Log("found comment");
    break;
   case XmlNodeType.EndElement:
    Debug.Log("found end element" + textReader.Name.ToString());
    break;
   default:
    Debug.Log("default out");
    break;
   }
  }

  textReader.Close();

  return result;
 }

所以我得到:

【问题讨论】:

  • 我没有看到与您看到的相同的行为。我复制了代码,做了一个小改动 Debug.Log -> Console.WriteLine,我看到配置文件被读取了三遍。你确定你正在阅读你认为你正在阅读的文件。在 while 语句的顶部尝试 textReader.ReadOuterXml() 以查看您正在阅读的文件中的确切内容。

标签: c# xml unity3d xmltextreader


【解决方案1】:

我的测试输出具有完全相同的代码和数据。 将 Debug.Log 替换为 Writeline。

default out
found comment
found profiles
default out
found profile
default out
found name
found text = One
found end elementname
default out
found date
found text = Two
found end elementdate
default out
found end elementProfile
default out
found profile
default out
found name
found text = One
found end elementname
default out
found date
found text = Two
found end elementdate
default out
found end elementProfile
default out
found profile
default out
found name
found text = One
found end elementname
default out
found date
found text = Two
found end elementdate
default out
found end elementProfile
default out
found end elementProfiles
default out

【讨论】:

  • 谢谢!,我发现 Debug.Log() 打印每个结果的速度都很慢。我不能使用 Console.WriteLine() 而是将每个结果连接到同一个字符串中,最后解析完成。
【解决方案2】:

这不是有效的 XML。 XML 规范只允许一个根节点(处理指令不算作节点),并且您的输入流包含多个根节点。如果你把它通过验证器,它会出错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2017-03-11
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多