我有一个包含节点和子节点的 XML 文件,某种类型的树视图。我想读取这些元素并提取内容以将它们写入具有新架构的新 XML 中,该架构具有更轻的树层次结构。
在我的代码中,我解析 XML 文件并读取节点和子节点,但我只能将节点打印到控制台。我无法弄清楚如何使用该方法的递归将节点写入 XML 结构中的新 XML。我是 XML 的菜鸟?我错过了什么吗?
XML 示例
<node clasification= some data about the node">
<dimension = some sort of info layer>
<children>
<node clasification= some data about the node">
<dimension = some sort of info layer>
<children>
<node clasification= some data about the node">
<dimension = some sort of info layer>
</children>
</node>
<node clasification= some data about the node">
<dimension = some sort of info layer>
</children>
</node>
</children>
</node>
</children>
</node>
我的代码基于此:
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("../../Employees.xml");
XmlNode root = doc.SelectSingleNode("*");
ReadXML(root);
}
private static void ReadXML(XmlNode root)
{
if (root is XmlElement)
{
DoWork(root);
if (root.HasChildNodes)
ReadXML(root.FirstChild);
if (root.NextSibling != null)
ReadXML(root.NextSibling);
}
else if (root is XmlText)
{}
else if (root is XmlComment)
{}
}
private static void DoWork(XmlNode node)
{
if (node.Attributes["Code"] != null)
if(node.Name == "project" && node.Attributes["Code"].Value == "Orlando")
Console.WriteLine(node.ParentNode.ParentNode.Attributes["Name"].Value);
}
请帮忙 :)
我找到了一种递归的方法。我无法共享最终代码,因为它位于无法访问互联网的封闭网络上,但基本上,我在 readxml 的开头创建了一个新节点,并在最后返回它,因此我无法将子对象发送给它递归...
类似的东西(伪代码)
private static XmlNode ReadXML(XmlNode root)
{
XmlNode tmp = new XmlNode;
// pupulate the node attributes
tmp = DoWork(root);
foreach (xmlnode childnode in node.childnodes)
{
if (check if you want this node)
{
XmlNodeList tmplist = childnode.childnodes;
if (tmplist.HasChildNodes)
{
tmp.newnode = new ChildNode[tmplist.count];
for (i=0;i<tmpnode.count;i++)
{
tmp.tmpnode[i] = ReadXML(tmplist.item(i));
}
}
else
{}
}
}
现在它工作正常
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句