开发者

Dynamically building xml tree's during runtime using linq

开发者 https://www.devze.com 2023-01-24 14:24 出处:网络
This is a design question, to whet the guru\'s appetite. In a previous version, the code was using a path definition, i.e. /../../ to provide instructions on how to build artbitary xml documents. Th

This is a design question, to whet the guru's appetite.

In a previous version, the code was using a path definition, i.e. /../../ to provide instructions on how to build artbitary xml documents. The documents had to be correct according to xml schema, so the path's were essentially xpaths, being read and used in switch statements to call code to construct the doc. But don't get hung up on it.

For example the call when read in and coded

jim.set("/Alert/Source/DetectTime", "12:03:2010 12:22:21");

would create

<Alert> 
  <Source>
    <DetectTime>12:03:2010 12:22:21</DetectTime>
  </Source>
</Alert>

The jim.set just stores the tree in a particular context.

Now I'd like to use linq to xsd, to create the xml tree, but i'm still looking for some contruct that will enable a user to define how the tree will be constructed. XPath's are easy, but kinda bulky to implement, not elegant and I don't easy 开发者_运维百科mapping.

Any ideas, any programs, open source, research, anything would be apreciated. If I don't get an answer I'll offer a decent bounty in 3 days. Bob.


How about doing something like this:

public XDocument CreateXDocument(string path, string value)
{
    var parts = path.Split(new [] { '/', },
        StringSplitOptions.RemoveEmptyEntries);
    return new XDocument(this.CreateXElement(parts, value));
}

private XElement CreateXElement(IEnumerable<string> parts, string value)
{
    var content = parts.Count() == 1 ?
        (object)value :
        (object)this.CreateXElement(parts.Skip(1), value);
    return new XElement(parts.First(), content);
}

You can then run the code like this:

var xd = this.CreateXDocument("/Alert/Source/DetectTime", "12:03:2010 12:22:21");
Console.WriteLine(xd.ToString());

Which will produce:

<Alert>
  <Source>
    <DetectTime>12:03:2010 12:22:21</DetectTime>
  </Source>
</Alert>

I thought I might post a variation of the CreateXElement method that should be more readable. The functionality is the same and there may even be a marginal performance improvement.

private XElement CreateXElement(IEnumerable<string> parts, string value)
{
    var head = parts.First();
    var tail = parts.Skip(1);
    var content = tail.Any() ?
        (object)this.CreateXElement(tail, value) :
        (object)value;
    return new XElement(head, content);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消