基于 XPath 创建 XML 节点? [英] Create XML Nodes based on XPath?

查看:38
本文介绍了基于 XPath 创建 XML 节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道从 XPath 表达式以编程方式创建 XML 层次结构的现有方法吗?

Does anyone know of an existing means of creating an XML hierarchy programatically from an XPath expression?

例如,如果我有一个 XML 片段,例如:

For example if I have an XML fragment such as:

<feed>
    <entry>
        <data></data>
        <content></content>
    </entry>
</feed>

给定 XPath 表达式/feed/entry/content/@source 我会有:

Given the XPath expression /feed/entry/content/@source I would have:

<feed>
    <entry>
        <data></data>
        <content @source=""></content>
    </entry>
</feed>

我意识到使用 XSLT 可以做到这一点,但由于我试图完成固定转换的动态特性,这将不起作用.

I realize this is possible using XSLT but due to the dynamic nature of what I'm trying to accomplish a fixed transformation won't work.

我正在使用 C#,但如果有人有使用其他语言的解决方案,请加入.

I am working in C# but if someone has a solution using some other language please chime in.

感谢您的帮助!

推荐答案

在您展示的示例中,唯一被创建的是属性...

In the example you present the only thing being created is the attribute ...

XmlElement element = (XmlElement)doc.SelectSingleNode("/feed/entry/content");
if (element != null)
    element.SetAttribute("source", "");

如果您真正想要的是能够在它不存在的地方创建层次结构,那么您可以使用自己的简单 xpath 解析器.我不知道如何将属性保留在 xpath 中.我宁愿将节点转换为元素并添加 .SetAttribute,就像我在这里所做的那样:

If what you really want is to be able to create the hierarchy where it doesn't exist then you could your own simple xpath parser. I don't know about keeping the attribute in the xpath though. I'd rather cast the node as an element and tack on a .SetAttribute as I've done here:


static private XmlNode makeXPath(XmlDocument doc, string xpath)
{
    return makeXPath(doc, doc as XmlNode, xpath);
}

static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath)
{
    // grab the next node name in the xpath; or return parent if empty
    string[] partsOfXPath = xpath.Trim('/').Split('/');
    string nextNodeInXPath = partsOfXPath.First();
    if (string.IsNullOrEmpty(nextNodeInXPath))
        return parent;

    // get or create the node from the name
    XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
    if (node == null)
        node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));

    // rejoin the remainder of the array as an xpath expression and recurse
    string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
    return makeXPath(doc, node, rest);
}

static void Main(string[] args)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<feed />");

    makeXPath(doc, "/feed/entry/data");
    XmlElement contentElement = (XmlElement)makeXPath(doc, "/feed/entry/content");
    contentElement.SetAttribute("source", "");

    Console.WriteLine(doc.OuterXml);
}

这篇关于基于 XPath 创建 XML 节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆