问题描述
|
对于我的入门级C#编程类,我们实际上是在编码自己的XML解析器(使用FileStream和ReadByte())
我们有一个“ test.xml”文件,该文件...
(我的老师将容器与父元素互换使用,并使用属性作为子元素,他对那些了解xml的人有些困惑,但他的课程针对的是不了解任何xml的那些人)
<containers>
<container>
<attribute1>data for attribute1 of container1</attribute1>
<attribute2>data for attribute2 of container1</attribute2>
<attribute3>data for attribute3 of container1</attribute3>
</container>
///more containers with varying amounts of attributes
...
</containers>
现在在他的示例解析器中(我们应该研究并做自己的版本,我们可以使用他的结构,但他更喜欢我们对其进行一些切换),他使用了一个常量
const string XMLCONTAINER = \"container\"
检查我们是否在父元素内,或者我们是否正在处理容器的子元素
if(!gInsideContainer) {
if(String.Compare(gParsetoken,XMLCONTAINER)==0) {
Console.WriteLine(\"\\n***** BEG OF CONTAINER\\n\");
gInsideContainer=true;
// save the offset of the beginning of the
// container into the container object
setAttribute(\"BEGPTR\",gTagOffset.ToString());
}
在我看来,这是不好的mojo,因为这意味着我必须使用最终要处理的每种xml类型来编辑源代码,以便弄清楚我们是否在父元素中。考虑到我们要研究的代码,我试图考虑如何进行更通用的检查,以查看我是否在父元素中,或者在子元素中。父元素。
我正在考虑创建一个数组来保存打开的元素,或者另一个字符串变量来保存当前打开的父元素,然后检查其关闭元素,但是这可能无法实现我想实现的方式赶上最初
<containers>
并在其余的解析过程中将insideContainer设置为true(是的,逻辑错误,至少我可以在编码之前发现这一点,呵呵)
我不允许使用任何.net XML解析类,(因为我们基本上是用较少的功能和可能不太有效的方式重写它,但是他在解决问题和创建算法方面的经验更多, (旨在教学)
关于如何实施我的想法有什么建议吗? (记住,这里是初级程序员。)
非常感谢您的帮助和建议!
解决方法
每次解析新的入口标签并在退出时从堆栈中弹出顶部标签的一种更通用的方式,将元素推入堆栈。如果您需要知道您的父标签是什么,可以查看一下。
最好还是创建一个树结构,其中每个节点都包含子节点列表,每个子节点都包含指向其父节点的链接,例如
public class Node
{
public string Name {get; private set;}
public List<Node> Children {get;set;}
public Node Parent {get; private set}
public int ElementDepth
{
get{ return Parent == null ? 1 : Parent.Depth + 1; }
}
public Node(string name,Node parent)
{
this.Name = name;
this.Children = new List<Node>();
this.Parent = parent;
}
public Node(byte[] xml,ref int startAt)
{
if(this.Depth == 2)
{
Console.WriteLine(\"In Container named \\\"\" + this.Name +\"\\\"\");
}
/* in this function:
* Get the tag name and either (recursively) create its children
* or return if it closes this tag
*/
}
}
那么总的来说,您所要做的就是将字节加载到内存中并调用Node(myArray,ref myIndexPointer)
,只要正确定义了该函数即可。