How to write CData of XML which contain inner nodes in C#? - c#

I have following xml document
<Node id="1" name="name1" autoplayTrailer="false" visible="true" bgimages="false">
<Text>
<title id="2" type="text" hideineditor="false" visible="true"><![CDATA[Link]]></title>
<sections id="3" default="consideration">
<songs id="4" type="text" hideineditor="false" enabled="true" visible="true">
<![CDATA[
<div class="ThumbContainer">
Some text here
</div>
]]>
<songsTitle><![CDATA[sometexthtml here]]></songsTitle>
</songs>
</sections>
</Text>
</Node>
I want to read the content/node one by one and modify the CDATA content and write the xml to disc.
Problem is i am not able to write the CData for <songs> node becoz it has another node inside <songTitle> node without closing the </song> node is it possilbe to write node with CData having another node following CData content?

Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement node in doc.Descendants("Node"))
{
XElement songs = node.Descendants("songs").FirstOrDefault();
XCData child = (XCData)songs.FirstNode;
string childStr = child.ToString();
childStr = childStr.Replace("Some text here", "Some text there");
child.ReplaceWith(childStr);
}
}
}
}

Is this the output you want to create?
This example outputs the CData & 'other element' under the 'songs' element using the XmlTextWriter API.
using System;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace WriteCData
{
class Program
{
static void Main(string[] args)
{
// some output to write to
XmlTextWriter xtw = new XmlTextWriter(#"c:\temp\CDataTest.xml", null);
// start at 'songs' element
xtw.WriteStartElement("songs");
xtw.WriteCData("<div class='ThumbContainer'>Some text here</div>");
xtw.WriteStartElement("songsTitle");
xtw.WriteCData("sometexthtml here");
xtw.WriteEndElement(); // end "songTitle"
xtw.WriteEndElement(); // end "songs"
xtw.Flush(); // clean up
xtw.Close();
}
}
}
output:
<songs>
<![CDATA[<div class='ThumbContainer'>Some text here</div>]]>
<songsTitle><![CDATA[sometexthtml here]]></songsTitle>
</songs>
The idea is to replace the static text used in the example with the values you read from your source document you mention in your question.

Related

Altering string variable storing xml in c#

string content = ....
I have some XML content stored in a string as shown in the variable above. The content stored is similar to below ,
<?xml version="1.0"?>
<model xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<ItemModel xsi:type="TypeKeep">
<Name>Name01</Name>
</ItemModel>
<ItemModel xsi:type="TypeDelete">
<Name>Name02</Name>
</ItemModel>
<ItemModel xsi:type="TypeDelete">
<Name>Name03</Name>
</ItemModel>
</Items>
</model>
In here I want to remove all the elements which have the type="TypeDelete" . In the sense I am trying to alter the content variable by removing the elments of TypeDelete
Any idea how I can achieve this ?
Using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
XDocument doc = XDocument.Parse(xml);
XNamespace xsiNs = doc.Root.GetNamespaceOfPrefix("xsi");
List<XElement> removeNodes = doc.Descendants("ItemModel").Where(x => (string)x.Attribute(xsiNs + "type") == "TypeDelete").ToList();
for (int i = removeNodes.Count - 1; i >= 0; i--)
{
removeNodes[i].Remove();
}
}
}
}
If you want to remove a specific XML node from an XML file directly you can go through this link and try this

Modifying two fields in .XML file

I have a XML file which looks like:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<UFCC xmlns="http://actel.com/sweng/afi">
<Region name="Region_0_0">
<content>
<static_data>
<fixed>
<value>11111111111111111111111111111111</value>
<type>HEX</type>
</fixed>
</static_data>
</content>
<region_start_word>0</region_start_word>
<number_of_word>16</number_of_word>
<simulation_value>
<value>11111111111111111111111111111111</value>
<type>HEX</type>
</simulation_value>
</Region>
<Region name="Region_1_0">
<content>
<static_data>
<fixed>
<value>BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB</value>
<type>HEX</type>
</fixed>
</static_data>
</content>
<region_start_word>16</region_start_word>
<number_of_word>16</number_of_word>
<simulation_value>
<value>BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB</value>
<type>HEX</type>
</simulation_value>
</Region>
<Program_Pages/>
</UFCC>
I'm trying to change value fields "11111111111111111111111111111111" to "A...A". I have tried this with Xml.Linq and using examples found online, from which none seem to work.
How can I modify these fields?
Sorry about the formatting, I'm not that familiar with proper XML formatting and the source file is written in single line.
You need to use the namespace :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
List<XElement> values1s = doc.Descendants(ns + "value").Where(x => (string)x == "11111111111111111111111111111111").ToList();
foreach (XElement x in values1s)
{
x.SetValue(((string)x).Replace("1", "A"));
}
}
}
}

XML File Editing with C#

So its my first time working with XML documents and i need some help.
I have this segment in my XML file:
<configuration>
<appSettings>
<add key="PhoneVersion" value="36.999.1" />
<add key="TabletVersion" value="36.999.1" />
<add key="DesktopVersion" value="36.999.1" />
</appSettings>
</configuration>
I am trying to read the Value of each line and increment the final digit by +1.
I am able to read the entire file however i just want to read the lines stated.
Any help??
Try using Xml Linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication51
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement add in doc.Descendants("add"))
{
string[] values = add.Attribute("value").Value.Split(new char[] {'.'});
values[values.Length - 1] = (int.Parse(values[values.Length - 1]) + 1).ToString();
add.SetAttributeValue("value", string.Join(".", values));
}
}
}
}
Use XElement to load the xml file. Then you can iterate the descendant nodes of the <configuration> node with the method Descendants().
Finally you can read the attributes of the <add> nodes with Attribute().

Read from 2 XML files using StreamReader

Assuming I have the following XML files:
Sample1.xml
<?xml version="1.0" encoding="utf-8"?>
<Root>
<NodeA>
<Node1>test1</Node1>
<Node1>test2</Node1>
</NodeA>
</Root>
Sample2.xml
<?xml version="1.0" encoding="utf-8"?>
<Root>
<NodeB>
<Node1>test1</Node1>
<Node1>test2</Node1>
</NodeB>
</Root>
My goal is to deserialize those 2 xml files using one factory method.
For that I have the following generic code:
public static T get<T>() where T : class // class = all reference types
{
string Ttype = typeof(T).Name;
using (var streamReader1 = new StreamReader(directoryPath + #"\Sample1.xml"))
using (var streamReader2 = new StreamReader(directoryPath + #"\Sample2.xml"))
using (var xmlReader ??? = XmlReader.Create(streamReader))
{
...
}
}
Built both xml files with the same root element.
My question is, since the xmlReader create function accepts only 1 stream reader.
How in the name of *, do i read with the xml reader from 2 xmls?
Do I combine 2 streams into 1 and read from 1st bit to the last 1, if so, how?
Thanks in advance,
Montana.
I would do it like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME1 = #"c:\temp\test.xml";
const string FILENAME2 = #"c:\temp\test2.xml";
static void Main(string[] args)
{
XDocument doc1 = XDocument.Load(FILENAME1);
XElement root1 = (XElement)doc1.FirstNode;
XDocument doc2 = XDocument.Load(FILENAME2);
XElement root2 = (XElement)doc2.FirstNode;
root1.Add(root2.Elements());
}
}
}

Select InnerText of XML is decoding URL

My issue is, when selecting a node from xml file (packet in my case) is decoding an url that is the inner text of the node within the xml. Example
<url>"http://my.xml.org/?id=AAA%2DDDD%3dNNNLKLKJLKL%2"</url>
using an instance of XmlDocument:
xmlDoc.SelectSingleNode("url").InnerText;
The string that is returned is: "http://my.xml.org/?id=AAA/DDDD/NNNLKLKJLKL/"
How do I prevent this from happening? Notice that the %2 and %3's have been changed to forward slashes.
The code below gets correct results. What are you doing differently?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<url>\"http://my.xml.org/?id=AAA%2DDDD%3dNNNLKLKJLKL%2\"</url>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string results = xmlDoc.SelectSingleNode("url").InnerText;
}
}
}
​

Categories