How to create xml element runtime? - c#

I need to create xml element in runtime in the existing xml file. How do i do that in c#?
For example, there is a xml file as
<data value = "1">
<user>one</user>
</data>
I want to create a element in runtime and output should be like this,
<data value = "1">
<user>one</user>
<status>used</status>
</data>

Use AooendChild() to add new child node. Try Something like following
XmlDocument doc = new XmlDocument();
XmlNode root = doc.DocumentElement;
//Create a new node.
XmlElement elem = doc.CreateElement("Status");
elem.InnerText="used";
//Add the node to the document.
root.AppendChild(elem);

Related

Reading XML file results in index out of range exception

Using C# I have an XML file like
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account>
<name>Jani</name>
</Account>
</root>
and I also have a function to read the name node as:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("lib//user.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
label1.Text = name.ToString();
but I am getting index out of range error as:
Why is this happening?
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
node is your root node. Which looks like this:
<root>
How many attributes does it have? None, as it turns out. An attribute in XML is one of these bar="baz" things:
<foo bar="baz">
node.Attributes[0] refers to the first attribute. There is no first attribute, there's no second attribute -- you didn't use attributes in this XML at all. Hence, that's out of range. There's no first item in an empty collection.
What you want is an element named name, which is farther down inside your XML tree.
Probably this:
var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");
And then you'll want to look at node.InnerText to get "Jani" out of it.
You are trying to read node.Attributes[0].Value but there is no attribtues in your sample XML file. Not sure of the exact syntax but it should probably be closer to node.Value
As mentioned by other answers, your current XML does not have attributes.
private void DoIt()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
//string name = node.Attributes[0].Value;
string name = node["Account"].InnerText;
}
If your XML did have attributes
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account name="Jani" />
</root>
Then you could do this:
private void DoItAgain()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data2.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node["Account"].Attributes[0].Value;
}

Getting nsi:type in xml

So I have a XML File that looks like this
<MyObjectBuilder_Sector xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SectorObjects>
<MyObjectBuilder_EntityBase xsi:type="MyObjectBuilder_CubeGrid">
<EntityId>-8358349049537298307</EntityId>
<LinearVelocity x="0" y="0" z="0" />
</MyObjectBuilder>
</SectorObjects>
</MyObjectBuilder_Sector>
I was curious how in C# how I could retrieve that MyObjectBuilder_CubeGrid from the MyObjectBuilder_EntityBase node. The best i got is this
fileLoc = ofd.FileName;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(fileLoc);
XmlNode typeOfNode = xdoc.SelectSingleNode("MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase").ToString();
Which of course just gets me the node not the xsi:type of the node. I've looked all over for it and can not find an answer.
-Cheers
     Jacob Bender
You can access node's attribute this way :
XmlNode typeOfNode =
xdoc.SelectSingleNode("MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase");
//here typeValue variable will contains "MyObjectBuilder_CubeGrid"
String typeValue = typeOfNode.Attributes["xsi:type"].Value;

C# how to create a custom xml document

I'm really just trying to create a custom xml document for simple configuration processing.
XmlDocument xDoc = new XmlDocument();
string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie"};
foreach (string node in NodeArray)
{
XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element,node.Split('|')[0],null);
//xmlNode.Value = node.Split('|')[0];
xmlNode.InnerText = node.Split('|')[1];
xDoc.DocumentElement.AppendChild(xmlNode);
}
What i'm trying to get is this.
<?xml version="1.0" encoding="ISO-8859-1"?>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>
i get not set to value of an object at xDoc.DocumentElement.AppendChild(xmlNode);
Unfortunately, You can't make that XML structure.
All XML documents must have a single root node. You can't have more.
Try something like this
XmlDocument xDoc = new XmlDocument();
xDoc.AppendChild( xDoc.CreateElement("root"));
string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie" };
foreach (string node in NodeArray)
{
XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element, node.Split('|')[0], null);
//xmlNode.Value = node.Split('|')[0];
xmlNode.InnerText = node.Split('|')[1];
xDoc.DocumentElement.AppendChild(xmlNode);
}
It is not possible to have that XML structure as XML MUST have a single root element. You may want to try:
<?xml version="1.0" encoding="ISO-8859-1"?>
<items>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>
</items>

How to Remove Root Element in C#/

I'm new to XML & C#.
I want to remove root element without deleting child element.
XML file is strudctured as below.
<?xml version="1.0" encoding="UTF-8"?>
<dataroot generated="2013-07-06T20:26:48" xmlns:od="urn:schemas-microsoft-com:officedata">
<MetaDataSection>
<Name>KR04</Name>
<XMLCreationDate>02.05.2013 9:52:41 </XMLCreationDate>
<Address>AUTOMATIC</Address>
<Age>22</Age>
</MetaDataSection>
</dataroot>
I want to root element "dataroot", so it should look like below.
<?xml version="1.0" encoding="UTF-8"?>
<MetaDataSection>
<Name>KR04</Name>
<XMLCreationDate>02.05.2013 9:52:41 </XMLCreationDate>
<Address>AUTOMATIC</Address>
<Age>22</Age>
</MetaDataSection>
Deleting child elements look like easy, but I don't know how to delete root element only.
Below is the code I've tried so far.
XmlDocument xmlFile = new XmlDocument();
xmlFile.Load("path to xml");
XmlNodeList nodes = xmlFile.SelectNodes("//dataroot");
foreach (XmlElement element in nodes)
{
element.RemoveAll();
}
Is there a way to remove root element only? without deleting child elements?
Thank you in advnace.
Rather than trying to actually remove the root element from an existing object, it looks like the underlying aim is to save (or at least access) the first child element of the root element.
The simplest way to do this is with LINQ to XML - something like this:
XDocument input = XDocument.Load("input.xml");
XElement firstChild = input.Root.Elements().First();
XDocument output = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
firstChild);
output.Save("output.xml");
Or if you don't need the XML declaration:
XDocument input = XDocument.Load("input.xml");
XElement firstChild = input.Root.Elements().First();
firstChild.Save("output.xml");
if you need to do in c# coding means
Solution
foreach (XElement item in Element.Descendants("dataroot").ToList())
{
item.ReplaceWith(item.Nodes());
}

inserting xml element into multiple nodes

I have the following XML
<ROOT>
<FSM338_Container>
<FSM338_Details>
<RunDate>2013-05-29 09:43:00</RunDate>
<Uic>21690</Uic>
<Date>2013-06-10 00:00:00</Date>
<CASHBREAK>199</CASHBREAK>
<CASHLUNCH>199</CASHLUNCH>
</FSM338_Details>
<FSM338_Details>
<RunDate>2013-05-29 09:43:00</RunDate>
<Uic>21690</Uic>
<Date>2013-06-10 00:00:00</Date>
<CASHBREAK>199</CASHBREAK>
<CASHLUNCH>199</CASHLUNCH>
</FSM338_Details>
</FSM338_Container>
<BillingReport>
<RunDate>2013-05-29 09:43:00</RunDate>
<Uic>21690</Uic>
<Date>2013-06-10 00:00:00</Date>
<gaindacd>1</gaindacd>
<docnum>07000F</docnum>
</BillingReport>
<DataElements>
<unitid>12345</unitid>
<fbocost>0.00</fbo>
</DataElements>
</ROOT>
I need to load the xml doc and add in several elements whenever I find the element named "Uic" . In short if I find "Uic" add in the element <someElement>my stuff here</someElement> at the same level as UIC at all locations.
I'Ve used
XmlDocument xDoc = new XmlDocument();
xDoc.Load(#"path_to_xml.xml");
list = xDoc.GetElementsByTagName("Uic");
I used insertBefore to add in my element but I can get it to copy to only the first element
You can use SelectNodes() method of XmlNode which accepts xpath expression.
XmlNodeList nodes = xDoc.DocumentElement.SelectNodes("Uic");
foreach(XmlNode node in nodes) {
XmlElement element = xDoc.CreateElement("SomeElement");
element.InnerText = "anything";
node.ParentNode.AppendChild(element);
}

Categories