xml 解析 - 编码 C# XML 字节解析器(用于类),一种判断我是属于父元素还是子元素的方法



对于我的入门级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 CONTAINERn");
    gInsideContainer=true;
    // save the offset of the beginning of the
    // container into the container object
    setAttribute("BEGPTR",gTagOffset.ToString());
 }

在我看来,这似乎是一个坏主意,因为这意味着我必须用我们最终处理的每种类型的xml编辑源代码,以确定我们是否在父元素中。我想,考虑到我们必须研究的代码,我如何做一个更通用的检查,看看我是在父元素中,还是在父元素的子元素中。

我正在考虑创建一个数组来保存打开的元素,或者创建另一个字符串变量来保存当前打开的父元素,然后检查它的关闭元素,但这可能不起作用,因为我正在考虑实现它的方法会捕获初始

<containers>

并在剩下的解析中将internalContainer设置为true(是的逻辑错误,至少我可以在编码前发现这个错误,呵呵)

我不被允许使用任何.net XML解析类,(因为我们基本上是用较少的功能重写它,可能效率较低,但更多的是他想要教授的解决问题和创建算法的经验)

关于我该如何着手实施我的想法,有什么建议吗?(记住,这里是初级程序员,哈哈)

非常感谢您的帮助和建议!

每次解析新的entry标记时,将元素推入堆栈的一种更通用的方法,并在退出时从堆栈中弹出顶部标记。如果你需要知道你的父母标签是什么,你可以偷看一下。

更好的方法是创建一个树结构,其中每个节点都包含子节点列表,每个子节点都包含到其父节点的链接,类似

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),只要该函数定义正确,你就完成了。

最新更新