【发布时间】:2018-09-04 08:07:57
【问题描述】:
我有一个包含两个开始标签和结束标签的 xml 文件。我需要这两个标签中的内容分别。请检查以下内容。
<testing>
<test>
<text>test1</text>
</test>
<test>
<text>test2</text>
</test>
</testing>
到目前为止,我正在使用 while 循环并查找标签的开始索引和结束索引,然后使用 substring 方法获取内容。请检查以下代码。
string xml = File.ReadAllText(@"C:\testing_doc.txt");
int startindex = xml.IndexOf("<test>");
while (startindex > 0)
{
int endIndex = xml.IndexOf("</test>", startindex);
int length = endIndex - startindex;
string textValue = xml.Substring(startindex, length);
startindex = xml.IndexOf("<test>", endIndex); // getting the start index for the second test tag
}
有没有其他方法可以在不使用 while 循环的情况下获取内容?因为使用 while 似乎有点昂贵,如果文本文件损坏,则会导致其他问题。
提前致谢, 阿尼什
【问题讨论】:
-
您可以使用正则表达式在一条指令中解析所有字符串,但您应该考虑完全采用不同的方法并使用内置的 int XML 相关类,这些会更值得信赖并且可能更容易使用。
-
"如果文本文件损坏,那么它会导致其他问题"。恕我直言,如果文件已损坏,您不应尝试读取它,如果已损坏,您如何确定其数据正常?
-
为什么while循环很贵?
-
如果是xml文件,为什么会有.txt扩展名?我知道,我在这里很挑剔,但这会在 我的 头脑中引发红旗......
标签: c# xml xml-parsing