Xml File Creation Using Xdocument in C#

XML file creation using XDocument in C#

LINQ to XML allows this to be much simpler, through three features:

  • You can construct an object without knowing the document it's part of
  • You can construct an object and provide the children as arguments
  • If an argument is iterable, it will be iterated over

So here you can just do:

void Main()
{
List<string> list = new List<string>
{
"Data1", "Data2", "Data3"
};

XDocument doc =
new XDocument(
new XElement("file",
new XElement("name", new XAttribute("filename", "sample")),
new XElement("date", new XAttribute("modified", DateTime.Now)),
new XElement("info",
list.Select(x => new XElement("data", new XAttribute("value", x)))
)
)
);

doc.Save("Sample.xml");
}

I've used this code layout deliberately to make the code itself reflect the structure of the document.

If you want an element that contains a text node, you can construct that just by passing in the text as another constructor argument:

// Constructs <element>text within element</element>
XElement element = new XElement("element", "text within element");

Creating xml with xdocument

Each object "device" have List<> of "functions", how can i add "functions" to xml???

Really easily - LINQ to XML makes this a doddle:

document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions",
functions.Select(f =>
new XElement("Function",
new XAttribute("Number", f.ID),
new XAttribute("Name", f.Name))))));

In other words, you just project your List<Function> to an IEnumerable<XElement> using Select, and the XElement constructor does the rest.

Creating XML using XDocument with Object that has two Lists

On the first iteration, you create a Document element, populate the fields, and add the Address element. On the second iteration, you add a second Document element, populate the fields, and then add an Address element to the FIRST Document element (rootElement.Element("DOCUMENT") gets the first "DOCUMENT" element).

https://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element(v=vs.110).aspx

I would instead create each new "DOCUMENT", including the Address, then add that to DOCUMENTS.

foreach (var pdf in PDFDocInfo) {
// create a "Document" element
newDoc = new XElement("DOCUMENT",
new XElement("Field_1", pdf.F1),
new XElement("Field_2", pdf.F2),
new XElement("Field_3", pdf.F3),
new XElement("Field_4", pdf.F4),
);
// add any Address elements to newDoc
foreach (var address in pdf.Address) {
newDoc.Add(
new XElement("Address",
new XElement("Item1", address.I1),
new XElement("Item2", address.I2));
}
}
// add newDoc to Documents
rootElement.Add(newDoc);
}

Writing to XML using XDocument, but knowing where to write

Try this out. I think this should get you what you want assuming the XML exists beforehand since you are calling createAndLoadXML before this method. I wrote this in NotePad++, so I may have a error or two.

private void writeToXML()
{
// Method to write lines to XML file based on user input
// Sets string variables
string fileName = softwareNameTextBox.Text;
string filePath = filePathTextBox.Text;
string fileType = installerType.Text.ToString();
string installSwitches = installSwitchesTextBox.Text;

string FILE_PATH = "bla.xml";

XDocument xDoc = XDocument.Load(FILE_PATH);

xDoc.Root.Add(new XElement("software_entry",
new XAttribute("name", fileName),
new XAttribute("path", filePath),
new XAttribute("type", fileType),
new XAttribute("switches", installSwitches)
));
xDoc.Save(FILE_PATH);
}

LINQ and XDocument: How to create XML file?

It's not clear exactly why the "Level" attributes are as specified, but this would create the relevant XML for you:

// Used for side-effects in the XElement constructor. This is a bit icky. It's
// not clear what the "Name" part is really for...
int count = 1;

var doc = new XDocument(
new XElement("FileDetails",
new XElement("Date", new XAttribute("FileModified", DateTime.UtcNow)),
l_lstData1.Select(x => new XElement("Data",
new XAttribute("Name", "Data_" + count++),
new XAttribute("DataList", x),
new XAttribute("Level", 2))),
l_lstData2.Select(x => new XElement("Data",
new XAttribute("Name", "Data_" + count++),
new XAttribute("DataList", x),
new XAttribute("Level", 1))),
l_lstData3.Select(x => new XElement("Data",
new XAttribute("Name", "Data_" + count++),
new XAttribute("DataList", x),
new XAttribute("Level", 0)))));

It would probably be neater if you could extract the projections from a list item to its element, but the "Data_" + count bit makes that tricky. It's not clear why you need such a thing to be honest... if you could get away without that, the code could be cleaner.

I suppose one alternative would be to create the document without the Name attributes, and then populate them afterwards. For example:

private static IEnumerable<XElement> ProjectList(IEnumerable<string> list,
int level)
{
return list.Select(x => new XElement("Data",
new XAttribute("DataList", x),
new XAttribute("Level", level)));
}

then:

var doc = new XDocument(
new XElement("FileDetails",
new XElement("Date", new XAttribute("FileModified", DateTime.UtcNow)),
ProjectList(l_lstData1, 2),
ProjectList(l_lstData2, 1),
ProjectList(l_lstData3, 0)));

int count = 1;
foreach (var element in doc.Descendants("Data"))
{
element.SetAttributeValue("Name", "Data_" + count++);
}

How to generate an XML file dynamically using XDocument?

Very simple

Please update your code accordingly

XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("children");
xml.AppendChild(root);

XmlComment comment = xml.CreateComment("Children below...");
root.AppendChild(comment);

for(int i = 1; i < 10; i++)
{
XmlElement child = xml.CreateElement("child");
child.SetAttribute("age", i.ToString());
root.AppendChild(child);
}
string s = xml.OuterXml;

How to save a XML file created in C# using XDocument in Root Folder

Have you tried to enter a path for the save file?

doc.Save("C:\Users\(name)\Documents\document.xml");

Or maybe promt user where to put file:

XDocument.Save(FolderBrowserDialog.SelectedPath + "\\" + "document.xml")

How to use XDocument to update existing xml file which has namespace requirements?

Try following :

            XDocument xml = XDocument.Load(_xmlFilePath);
XElement root = xml.Root;
XNamespace ns = root.GetDefaultNamespace();

root.Add(new XElement(ns + "Event",

how read a xml file with C# XDocument?

You can try using LINQ

var xdoc = XDocument.Load(XMLFile);

var items = from item in xdoc.Descendants("solidBodies").Elements("body")
select new
{
name = item.Element("name").Value,
density = item.Element("density").Value
};

foreach (var item in items)
{
Console.WriteLine($"{item.name} {item.density}");
}

OUTPUT

BLOCK(1) 1200
BLOCK(8) 7927,81
SPHERE(9) 7192


Related Topics



Leave a reply



Submit