how to remove nodes in an xml that is inside another xml - c#

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>

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();
}

Create a New xmlElement in 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);
}

LINQ - Specified elements not being removed from XML file

I have an XML file:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--QTabs Data Storage-->
<SyncTimes>
<LastSyncTime>
<id>1</id>
<SyncTime>3/31/2015 2:03:28 PM</SyncTime>
</LastSyncTime>
<LastSyncTime>
<id>2</id>
<SyncTime>3/31/2015 2:14:24 PM</SyncTime>
</LastSyncTime>
<LastSyncTime>
<id>3</id>
<SyncTime>3/31/2015 2:14:25 PM</SyncTime>
</LastSyncTime>
<LastSyncTime>
<id>4</id>
<SyncTime>3/31/2015 2:14:26 PM</SyncTime>
</LastSyncTime>
</SyncTimes>
All of the above times are earlier today I want to delete all LastSyncTime records before the current time (DateTime.Now):
public async void deleteArchivedSyncs()
{
var xElement = (from element in XMLDocObject.Elements("LastSyncTime")
where Convert.ToDateTime(element.Element("SyncTime").Value) < DateTime.Now
select element);
xElement.Remove();
storageFile = await storageFolder.GetFileAsync(Settings.xmlFile);
using (Stream fileStream = await storageFile.OpenStreamForWriteAsync())
{
XMLDocObject.Save(fileStream);
}
}
This being run does not effect the XML page. The desired elements are not being removed. What am I doing wrong?
This issue here appears to be that the only way to delete a child, is to have the parent do the deletion, as in:
class Program
{
public static void Main(params string[] args)
{
// test.xml contains OPs example content.
var xdoc = XDocument.Load(#"c:\temp\test.xml");
xdoc.Descendants("LastSyncTime")
.Where(e => Convert.ToDateTime(e.Element("SyncTime").Value) < DateTime.Now)
.Remove();
Console.WriteLine(xdoc);
xdoc.Save(#"c:\temp\test_filtered.xml");
}
}
This generates the following output:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--QTabs Data Storage-->
<SyncTimes />
I.e. an empty root, which is to be expected, given that all dates are smaller than DateTime.Now.
#DavidTunnell what is your root xml element that contains everything you need? in example:
//let's call the variable you use as Xdocument doc.
XmlNodeList nodes = doc.SelectNodes("LastSyncTime");
for (int i = nodes.Count - 1; i >= 0; i--)
{
nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save(path);
This is how i had used hope it helps.

XDocument.Root.Element returns null

I have XML which is like:
<?xml version="1.0" encoding="utf-16"?>
<RootNodeName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" MyAttribute="7" xmlns="mylink">
<IsValid>false</IsValid>
<Name>some matrix</Name>
...Some more nodes...
</RootNodeName>
and code which is like:
var doc = XDocument.Parse(myXmlString);
Console.WriteLine(doc.Root.Element("Name"));
and console shows just an empty space since doc.Root.Element("Name") returns null =(
While I can find this Element among doc.Root.Elements() results.
doc.Root.Attribute("MyAttribute") gives correct result as well.
What is wrong with it/me?
The <Name> element is in the mylink namespace:
XNamespace mylink = "mylink";
Console.WriteLine(doc.Root.Element(mylink + "Name"));

Changing an XML Child Element into a Parent

I have an xml document that has a structure like so:
<?xml version="1.0" encoding="iso-8859-1" ?>
- <newdataset xml="version="1.0" encoding="iso-8859-1"">
- <officelist>
<officeid>2</officeid>
<office>Office</office>
<region>BC</region>
I would like to have the office id = 2 to be its own element. Like so
<?xml version="1.0" encoding="iso-8859-1" ?>
<newdataset xml="version="1.0" encoding="iso-8859-1"">
<officelist>
<officeid id=2/>
<office>Office</office>
<region>BC</region>
</officeid>
</officelist>
</newdataset>
xmlDS += offices.GetXml();
xmlDS = xmlDS.Replace(#"xml:space=""preserve""", " ");
XmlDocument doc = new XmlDocument();
XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
doc.LoadXml(xmlDS);
doc.Save(Response.OutputStream);
That is my code so far... not sure how to set a child node to become a parent node
using XDocument made this a lot easier with Linq.

Categories