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

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

问题描述

有谁知道,从一个XPath前pression编程创建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 pression /料/项/内容/ @源我会:

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.

感谢您的帮助!

推荐答案

在这个例子中你所创建的唯一present是属性...

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天全站免登陆