使用Java中的Stacks查找一个XML文档是否有效。

问题描述 投票:-1回答:1

我需要用堆栈查找一个XML文档是否有效。谁能帮我弄清楚这个所需的算法。这让我困惑了很久,下面是程序的示例输出。

These are some example outputs for the program

java xml data-structures stack
1个回答
1
投票

使用提供的例子,你已经粘贴在上面。你可以很容易地使用堆栈来解决它。

首先,你需要一个方法,将一个输入作为标签,并返回两个对--不管它是打开还是关闭标签,其次是字符串名称。

例如:-当我调用方法-----------------------------。parseTag(String tag) ,让我们假设这里的例子标签是-----------------------------------------------------------------。<note> 所以它将返回- Tuple("note", true). 是的,因为它是开头的标签,而且在-的情况下。</note> ,该方法将返回- Tuple("note", false).

现在,一旦我们准备好了这个方法,就开始研究我们的算法吧。

1. Lets declare a stack in java using - Stack<String> st = new Stack<>();
2. Now, lets start to iterate over our xml, based on different tags.
3. Call method parseTag(tag) on our tags while looping over xml and if its an opening tag, then push it on top of stack.
4. Else if its a closing tag, then check whether the top of the stack has same tag name as the current closing tag, if they dont match, then return false and break out of loop.
5. If we reach the end of while loop, check whether the stack is empty or not, because if a stack is valid, then its supposed to be empty. If not then return false.
6. At the end, if you reach this step, then return true as we are sure our provided xml is perfectly valid.

希望这能帮助我们

© www.soinside.com 2019 - 2024. All rights reserved.