我试图解析具有特定格式的文本文件,并将其拆分为键值,以后我可以在外部编辑,这样我就可以将它们构建回另一个文本文件中。我尝试这样做的方式对我来说似乎很脏,我使用流来遍历文件,直到我通过使用while循环来达到引号和括号。它主要工作,直到我到达一个特定点,我要么偶然发现一个闭合支架或跳过一些完全搞砸了格式的终止引用。我尝试过一系列不同的改动,但它只是不能正常工作。
我试图解析的文件有这种格式:
testparse.txt
"testparse.txt"
{
"TestElement"
{
"value1" "0"
"value2" "stuff"
"value3" "morestuff"
"value4" "25"
"value5" "text"
"value6" "21"
}
"TestElement2"
{
"value1" "0"
"value2" "1"
"value3" "2"
"value4" "3"
"value5" "4"
"value6" "5"
}
}
我有兴趣将名称和值(" value1"," 0")打包到KeyValues中,我稍后将其打包到Elements中,然后将其打包到Files中。我为所有事情使用字符串。
这是我的代码: Program.cs的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace hudParse
{
class Program
{
static void Main(string[] args)
{
char qt = '\"';
StreamReader sr = new StreamReader("D:/Desktop/testparse.txt");
HudFile file = new HudFile();
string s = "";
Seek(sr,qt);
do
{
s += (char)sr.Read();
}
while(sr.Peek() != qt);
sr.Read();
file.Name = s;
Console.WriteLine("Filename is " + s);
Seek(sr,'{');
//Main loop
do
{
HudElement element = new HudElement();
Seek(sr,qt);
s = "";
do
{
s += (char)sr.Read();
}
while(sr.Peek() != qt);
sr.Read();
element.Name = s;
Console.WriteLine("New Element name is " + s);
Seek(sr,'{');
do
{
s = "";
KeyValue kv = new KeyValue();
Seek(sr,qt);
do
{
s += (char)sr.Read();
}
while(sr.Peek() != qt);
kv.Name = s;
sr.Read();
s = "";
Seek(sr,qt);
do
{
s += (char)sr.Read();
}
while(sr.Peek() != qt);
kv.Value = s;
sr.Read();
element.Add(kv);
Console.WriteLine("KeyValue added to " + element.Name + ": " + kv.ToString());
}
while(sr.Read() != '}');
}
while((sr.Read() != '}') || (sr.Read() != -1));
file.Write();
sr.Close();
Console.WriteLine("Created file " + file.Name);
}
static void Seek(StreamReader sr, char c)
{
while(sr.Read() != c);
}
}
}
KeyValue.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace hudParse
{
class KeyValue
{
string m_Name;
string m_Value;
public string Name
{
get
{
return m_Name;
}
set
{
m_Name = value.Trim();
}
}
public string Value
{
get
{
return m_Value;
}
set
{
m_Value = value.Trim();
}
}
public KeyValue()
{
m_Name = null;
m_Value = null;
}
public KeyValue(string name, string value)
{
m_Name = name;
m_Value = value;
}
public override string ToString()
{
return '\"'+ m_Name + '\"' + '\t' + '\t' + '\"'+ m_Value + '\"';
}
public string GetName()
{
return m_Name;
}
public string GetValue()
{
return m_Value;
}
public bool isNull()
{
if(m_Name == null)
return true;
return false;
}
}
}
我确信有一种更好的方法可以完成所有这些我不知道的事情,所以我不会让空格,制表符和换行符破坏我的解析。这是与我的代码相关的其他类。
答案 0 :(得分:1)
您的数据看起来像一个破碎的JSON,所以我认为解析它的最简单方法是将其转换为有效的JSON,然后使用一些默认工具,如JSON.NET。您的数据应该是
{
"t1": {
"key1":"value1",
"key2":"value2"
},
"t2": {
"key3":"value3",
"key4":"value4"
}
}
以上示例适用于Dictionary<string, Dictionary<string, string>>
类型。