Skip to content

Instantly share code, notes, and snippets.

@msarchet
Created April 14, 2011 21:28
Show Gist options
  • Save msarchet/920603 to your computer and use it in GitHub Desktop.
Save msarchet/920603 to your computer and use it in GitHub Desktop.
A Linq extension in the making that is for merging XML Documents.
using System;
using System.Linq;
using System.Xml.Linq;
public class Foo
{
public static void Main()
{
XDocument test = new XDocument();
//SetValue(test, "thing3", new object[] {"Root", "Blargh", "Node3", "ChildNode"});
//Console.WriteLine(test.ToString());
try
{
XDocument test2 = new XDocument(new XElement("Root1"));
SetValue(test2, "thing3", new object[] {new XDocument(new XElement("Root2"))});
Console.WriteLine(test2.ToString());
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
public static void SetValue (XContainer obj, object value, params object[] nodes)
{
XContainer workingNode = obj;
foreach(var node in nodes)
{
String nodeName = "notSet";
if (node is String)
{
nodeName = (String) node;
if(workingNode.Element(nodeName) == null)
{
workingNode.Add(new XElement(nodeName));
}
workingNode = workingNode.Element(nodeName);
}
//here we need to check and see for each node if the current working node contains a matching
//XContainer
if (node is XContainer)
{
var CurrentContainer = node;
if (((XContainer) node).Parent != null)
{
Console.WriteLine("Had Parent");
CurrentContainer = ((XContainer) node).Parent;
}
if(CurrentContainer is XDocument)
{
var Document = (XContainer) CurrentContainer;
Console.WriteLine("Working Node is = " + ((XDocument) workingNode).Elements().First().Name.ToString());
workingNode = enumerateDescendants(Document);
}
}
if(nodes.Last().Equals(nodeName) && value != null)
{
XElement addElement = (XElement) workingNode;
addElement.Value = value.ToString();
}
}
}
public static XContainer enumerateDescendants(XContainer container)
{
XContainer nodeCopy = container;
foreach(var element in container.Elements())
{
if (nodeCopy.Element(element.Name) == null)
{
nodeCopy.Add(element);
}
else if(element.Descendants().Any())
{
}
}
return nodeCopy;
}
}
@msarchet
Copy link
Author

The idea for this will be to allow someone to create, read, or merge XML documents on the fly without having to worry about null reference issues.

Still very early. If you want ot try it out uncomment the 6 lines near the end and try creating a document with something like

var testDocument = new XDocument();
SetValue(testDocument, null, new object() {"Root", "Child"});
SetValue(testDocument, "test Value", new object() {"Root", "Child1"});
Console.WriteLine(testDocument.ToString());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment