Create a New xmlElement in c# - c#

Hi i have a Problem I have this XML file as my Config file
<?xml version="1.0" encoding="utf-8"?>
<configs>
<config>
<starmade_path>null</starmade_path>
<gui_path>null</gui_path>
<first_start>true</first_start>
<dark_theme>false</dark_theme>
<light_theme>true</light_theme>
<OSM_theme>false</OSM_theme>
</config>
</configs>
And i need first to add a new Element if it doesent exist in the file so my XML file looks like this
<?xml version="1.0" encoding="utf-8"?>
<configs>
<config>
<starmade_path>null</starmade_path>
<gui_path>null</gui_path>
<first_start>true</first_start>
<dark_theme>false</dark_theme>
<light_theme>true</light_theme>
<OSM_theme>false</OSM_theme>
<Red_theme>sampleText</Red_theme>
</config>
</configs>

Use this code, this code add starmade_path if not present, this way you can check and add other nodes too
XDocument doc = XDocument.Load(#"D:\a.XML");
XElement root = doc.Element("configs");
XElement config = root.Element("config");
XElement starmade_path = config.Element("starmade_path");
if (starmade_path == null)
{
XElement n = new XElement("starmade_path");
n.Value = "aljd";
config.Add(n);
doc.Save(#"D:\a.XML");
}

Try this. It will add Red_theme if not exists in xelement.
XDocument xml = XDocument.Load("yourfile");
XElement configelement= xml.Descendants("config").First();
XElement element = configelement.Elements().FirstOrDefault(x => x.Name== "Red_theme");
if (element == null)
{
element = new XElement("Red_theme");
element.Value = "sampletext";
configelement.Add(element);
}

Related

Change ALL Tag Name to Lowercase inside XMLDocument

I need to change ALL the Tag name to Lowercase but leave the InnerText or Value as it is. I just found the thread showing how to change the casing for the entire document but NOT just for the Tag names.
Code
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlDoc.OuterXml.ToLower());
Original.xml
<?xml version="1.0" encoding="utf-8" ?>
<ROOT>
<InNeRtAg>SoMe TeXt</InNeRtAg>
<NeStEdElEmEnT>
<InNeRnEsTiNg>SoMe TeXt</InNeRnEsTiNg>
</NeStEdElEmEnT>
</ROOT>
Changing ALL nodes including the root element:
var doc = XDocument.Load("Original.xml");
// also need to change the root element
doc.Root.Name = doc.Root.Name.LocalName.ToLower();
foreach (var element in doc.Descendants().Elements())
{
element.Name = element.Name.LocalName.ToLower();
}
doc.Save("Modified.xml");
Results in Modified.xml
<?xml version="1.0" encoding="utf-8"?>
<root>
<innertag>SoMe TeXt</innertag>
<nestedelement>
<innernesting>SoMe TeXt</innernesting>
</nestedelement>
</root>
When using
foreach (var element in doc.Descendants().Elements())
{
element.Name = element.Name.LocalName.ToLower();
}
the root element will not be changed.
<?xml version="1.0" encoding="utf-8"?>
<ROOT>
<innertag>SoMe TeXt</innertag>
<nestedelement>
<innernesting>SoMe TeXt</innernesting>
</nestedelement>
</ROOT>
You can try something like this:
var doc = XDocument.Load(filepath);
foreach (var element in doc.Descendants().Elements())
{
element.Name = element.Name.LocalName.ToLower();
}

how to remove nodes in an xml that is inside another xml

I have an xml as an value of an element inside a Main xml. I want to scrub off or delete a node within the inner xml. How do I achieve that ?
For removing a node in main xml I am doing
var result = doc.Descendants("node1").Where(x => x.Attribute("id").Value == "002");
if (result != null)
{
result.Remove();
}
Here is my XML :
<?xml version="1.0" encoding="utf-16"?>
<root>
<node1>id="001" version="1.0"</node1>
<node2>id="002" version="1.0"</node1>
<report>raw = "<response = "10"><innerxml><prod>date = "18082016" name="pqr"</prod><seg1>id="002" name = "sqs"</seg1></innerxml></response>"</report>
</root>
Your code is correct but your xml is not. the XML should be like:
<?xml version="1.0" encoding="utf-16"?>
<root>
<node1 id="001" version="1.0"></node1>
<node2 id="002" version="1.0"></node2>
</root>

Very simple XML reading in C#.NET

I want to read the following XML file:
Words.xml:
<?xml version="1.0" encoding="utf-8" ?>
<words>
<word>Bat</word>
<word>Dog</word>
<word>Car</word>
</words>
..using XDocument. I keep getting a "Non white space characters cannot be added to content" error with this code:
XDocument doc = new XDocument("words.xml");
foreach (XElement element in doc.Descendants("word"))
{
Console.WriteLine(element.Value);
}
You need to load the document like this:
XDocument doc = XDocument.Load("words.xml");
The reason your original code fails is you are using XDocument (Object[]) constructor that normally expects list of XElement objects like:
var doc = new XDocument(new XElement("Root"));

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>

xml error:System.Xml.XPath.XPathException: Expression must evaluate to a node-set

I am trying to find a node in my xml file but getting the error ( see title)?
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\temp\test2.xml");
var node = doc.SelectSingleNode("/Offers/Offer/ID=[text()='1']");
var test = node;
xml
<?xml version="1.0" encoding="utf-8"?>
<Offers>
<Offer>
<Model>AAAA</Model>
<ID>1</ID>
<Name>First offer</Name>
</Offer>
<Offer>
<Model>BBBB</Model>
<ID>2</ID>
<Name>Second offer</Name>
</Offer>
</Offers>
Remove the = after ID:
var node = doc.SelectSingleNode("/Offers/Offer/ID=[text()='1']");
becomes:
var node = doc.SelectSingleNode("/Offers/Offer/ID[text()='1']");

Categories