我正在使用非确定性有限自动机构建一个应用程序,它必须保存它并从文件中读取它。我用 [XmlTags] 尝试了几十种不同的方法,但它仍然给我错误。你能告诉我应该如何定义类以由 XML 序列化程序序列化吗?
public class state
{
[XmlAttribute]
public string name
{ get; set; }
public List<transition> transitions
{ get; set; }
public state()
{
}
public state(string Name)
{
name = Name;
}
public void addTransition(string Letter, state NextState)
{
bool found = false;
foreach (transition tr in this.transitions)
{
if (tr.letter.Equals(Letter))
{
tr.nextStates.Add(NextState);
found = true;
break;
}
if (found == false)
{
transitions.Add(new transition(Letter, NextState));
}
}
if (found == false)
{
transitions.Add(new transition(Letter, NextState));
}
}
}
public class transition
{
[XmlAttribute]
public string letter
{ get; set; }
public List<state> nextStates
{ get; set; }
public transition()
{
}
public transition(string Letter, state NextState)
{
letter = Letter;
nextStates = new List<state>();
nextStates.Add(NextState);
}
}
public class automaton
{
public List<state> states
{ get; set; }
public automaton()
{
}
public bool isState(string StateName)
{
foreach (state st in states)
if (st.name.Equals(StateName)) return true;
return false;
}
public state getState(string StateName)
{
foreach (state st in states)
if (st.name.Equals(StateName)) return st;
return new state(StateName);
}
}
public class XMLReader
{
public static void NFAToXML(automaton Automaton, string Filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(automaton));
TextWriter textWriter = new StreamWriter(@Filename);
serializer.Serialize(textWriter, Automaton);
textWriter.Close();
}
public static automaton XMLToNFA(string Filename)
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<state>));
TextReader textReader = new StreamReader(Filename);
automaton automaton = new automaton();
automaton.states= (List<state>)deserializer.Deserialize(textReader);
textReader.Close();
return automaton;
}
}
我希望我的 XML 看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<automaton xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<state name="q0" type="initial" >
<transition letter="0">
<state name="q1"></state>
<state name="q3"></state>
</transition>
<transition letter="1">
<state name="q0"></state>
<state name="q2"></state>
</transition>
</state>
<state name="q1">
<transition letter="0">
</transition>
<transition letter="1">
<state name="q3"></state>
</transition>
</state>
<state name="q2" type="accepting">
<transition letter="0">
<state name="q1"></state>
</transition>
<transition letter="1">
<state name="q0"></state>
<state name="q2"></state>
</transition>
</state>
<state name="q3">
<transition letter="0">
<state name="q1"></state>
</transition>
<transition letter="1">
<state name="q1"></state>
<state name="q2"></state>
</transition>
</state>
</automaton>
请帮助,我试图以多种方式改变它,但没有成功......