how to insert (C#) variables in xml - c#

if i were to say create a function:
public static string createProduct(string pName, decimal pPrice)
{string postData = #"<?xml version=""1.0"" encoding=""UTF-8""?
<product>
<name>?</name>
<price>?</price>
</product>";
....some other codes...}
i have tried googling it but have not found any clear answer...
and sorry i'm kinda new to xml and c#, so how do i insert pName and pPrice into xml without upsetting visual studio?
would really appreciate help from you guys...tia!

var str = new XElement("product",
new XElement("name", pName),
new XElement("price", pPrice))
.ToString();
System.Xml.Linq Namespace and XElement class are good places to start to read and easier to use than System.Xml namespace

public static string createProduct(string pName, decimal pPrice)
{string postData = #"<?xml version=""1.0"" encoding=""UTF-8""?
<product>
<name>" + pName + #"</name>
<price>" + pPrice+ #"</price>
</product>";
....some other codes...}
I recommend that you take a look at constructing the XML document not by string concatenation as it is quite unreliable (what if pName contains angle brackets?). Try looking at the XElement (XLINQ) API.

A Google search for how to add variables to a string in c# yielded this page as the first result: Strings (C# Programming Guide)
You can use the + operator to concatenate strings (that compiles to the string.Concat method). Or, you could use string.Format; for more information on that, see the page on composite formatting. This approach is only suitable for the simplest of small XML fragments.
You also have several options in the form of different sets of classes that will help you build and work with XML, most of which are to be found in the System.Xml namespaces. These classes will produce well-formed XML, taking care of small details that you might overlook (for example, special handling of certain characters). Unfortunately, I don't know of a good discussion of the pros and cons of each approach.

I'd really recommend not doing this by string concatenation. There are a number of different ways to accomplish this that will yield better (as in less likely to produce malformed XML) results.
Via XmlTextWriter:
string xmlString = null;
using (StringWriter xmlOutput = new StringWriter())
using(XmlTextWriter xmlWriter = new XmlTextWriter(xmlOutput))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("product");
xmlWriter.WriteElementString("name", pName);
xmlWriter.WriteElementString("price", pPrice);
xmlWriter.WriteEndElement();
xmlString = xmlOutput.ToString();
}
Using XmlDocument:
string xmlString = null;
using (StringWriter xmlOutput = new StringWriter())
{
XmlDocument xmlDocument = new XmlDocument();
XmlElement productElement = xmlDocument.CreateElement("product");
XmlElement nameElement = xmlDocument.CreateElement("name");
nameElement.InnerText = pName;
XmlElement priceElement = xmlDocument.CreateElement("price");
priceElement.InnerText = pPrice;
productElement.AppendChild(nameElement);
productElement.AppendChild(priceElement);
xmlDocument.AppendChild(productElement);
xmlDocument.Save(xmlOutput);
xmlString = xmlOutput.ToString();
}
Using XDocument (requires that you are using .NET 3.5 or higher):
XDocument xml = new XDocument(
new XElement("product",
new XElement("name", pName),
new XElement("price", pPrice)
)
);
string xmlString = xml.ToString();
Note that of these methods only the one using XmlTextWriter will stream, which may be important for very large XML composition. If you are using .NET 3.5 or higher and are not dealing with very large XML composition, I would give preference to XDocument as it's a lot more readable and simpler to use.

Related

Quickly create XML in C# VS VB.net [duplicate]

Is it possible to add literal XML data within a C# code file? I'm currently using a multiline string literal but it gets messy as you can see. Any better way of doing this?
string XML = #"<?xml version=""1.0"" encoding=""utf-8""?>
<customUI xmlns=""http://schemas.example.com/customui"">
<toolbar id=""save"">
</toolbar>
</customUI>";
XML literals are a feature of VB.NET, not C#.
What you have posted is as close as you can get in C#.
You may want to consider replacing the embedded double quotes with single quotes though (as both types are valid XML).
For larger amounts of XML you may want to consider the answer from Marc - using an XML file (loaded once and stored in memory), so you can take advantage of the XML editor.
If the XML is big enough to get in the way, consider using a flat .xml file instead, either loaded from disk, or embedded as a resource. As long as you only load it once (perhaps in a static constructor) this will make no difference to performance. It will be considerably easier to maintain, as it will use the IDE's XML file editor. And it won't get in the way of your code.
With reference to my comment, I couldn't recall where I saw this, but I finally found the XmlBuilder link.
In retrospect, it seems Linq to XML would be your best bet. It's cleaner, faster and more maintainable than concatenating XML strings:
XNamespace ns = "http://schemas.example.com/customui";
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement(ns + "customUI",
new XElement(ns + "taskbar",
new XAttribute("id", "save"))
)
);
var stringWriter = new StringWriter();
doc.Save(stringWriter); //Write to StringWriter, preserving the declaration (<?xml version="1.0" encoding="utf-16" standalone="yes"?>)
var xmlString = stringWriter.ToString(); //Save as string
doc.Save(#"d:\out.xml"); //Save to file
As a peculiar, and very case-specific solution, if you happen to be working in an ASP.NET environment using the Razor engine, in a CSHTML file you can:
Func<MyType, HelperResult> xml = #<root>
<item>#(item.PropertyA)</item>
<item>#(item.PropertyB)</item>
<item>#(item.PropertyC)</item>
</root>;
With the addition of an extension method:
public static XDocument ToXDocument<T>(this Func<T, HelperResult> source, T item)
{
return XDocument.Parse(source(item).ToHtmlString());
}
You can then:
XDocument document = xml.ToXDocument(new MyType() {
PropertyA = "foo",
PropertyB = "bar",
PropertyC = "qux",
});
Again, peculiar? Yes. Case-specific? Yes. But it works, and gives great Intellisense. (mind you, it also will give a bunch of validity warnings, depending on the document validation version)
The closest we could have in C# would be through LINQ, something like that:
var xml = XDocument.Load(
new StringReader(#"<Books>
<Book author='Dan Brown'>The Da Vinci Code</Book>
<Book author='Dan Brown'>The Lost Symbol</Book>
</Books>"));
var query = from book in xml.Elements("Books").Elements("Book")
where book.Attribute("author").Value == "Dan Brown"
select book.Value;
foreach (var item in query) Console.WriteLine(item);

Trying to read particular Xml value using C#

I'm new with C#. please help me.
data.xml
<?xml version="1.0" standalone="yes"?>
<DataSet1 xmlns="http://tempuri.org/DataSet1.xsd">
<Language>
<Id>001</Id>
<English>"Welcome to India"</English>
<German>"Willkommen in Indien"</German>
</Language>
</DataSet1>
How to read value of Id using C# Xml? I'm new with C#. please help me.
My effort:
XmlDocument doc = new XmlDocument();
XmlReader reader = XmlReader.Create(#"D:\data.xml");
while(reader.Read())
{
reader.MoveToContent();
if (reader.IsStartElement("DataSet1"))
{
reader.ReadToDescendant("Language");
string str2 = reader.Name.ToString();
MessageBox.Show(str2);
}
}
I'd strongly advise you to use LINQ to XML, which is a much simpler API than XmlDocument, and has excellent namespace support. Here's an example to get the Id value with LINQ to XML:
using System;
using System.Xml.Linq;
public class Program
{
public static void Main()
{
XDocument doc = XDocument.Load("test.xml");
XNamespace ns = "http://tempuri.org/DataSet1.xsd";
string id = doc.Root // From the root...
.Element(ns + "Language") // select the Language direct child...
.Element(ns + "Id") // and the Id child of that...
.Value; // and then take the text value
Console.WriteLine(id);
}
}
Obviously if your XML doesn't just have a single Language element you'll need to pick the right one, etc. You should read the LINQ to XML documentation for more information.
Use XmlDocument, if you Need further help leave a comment :)
XmlDocument xdoc = new XmlDocument("YourXmlString");
XmlNodeList xNodes = xdoc.GetElementsByTagName("Id");
string Wished = xNodes[0].InnerText;
Little bit of explanation:
I recommend XmlDocument a lot because I really like to work with it myself, and besides that it has some pretty neat features to explore. Besides that, it is easy to get or to iterate through nodes

How to parse the below xml string in c#

I have the below xml string in one string variable.
string xmlString = "<a:ORegions>
<a:ID>1</a:ID>
<a:regionCode>US</a:regionCode>
</a:ORegions>
<a:ORegions>
<a:ID>2</a:ID>
<a:regionCode>CANADA</a:regionCode>
</a:ORegions>
<a:ORegions>
<a:ID>3</a:ID>
<a:regionCode>ASIA</a:regionCode>
</a:ORegions>
Now i want to access regionCode values, that is US, CANADA, ASIA
How i can do that using c#. I am new to xml parsing.
You can deserialize that string (assuming you fix the various syntax errors) via the System.Xml namespace classes, particularly XmlDocument, such as with its Load method. To access the namespaces (a in a:Oregions and such is a namespace), you'll want an XmlNamespaceManager. You'd then register the namespaces (they must be defined somewhere) with the manager and use that when querying the XmlDocument.
Use LinqToXml
var doc = XDocument.Parse(xmlString);
You can then access elements, values and attributes within:
XNamespace xmlNamespace = "a";
//e.g. Retrieve's a list of regioncodes...
var ids = doc.Elements(xmlNamespace + "ORegions")
.Select(r => r.Element("regionCode").Value);
XmlDocument document = new XmlDocument();
document.Load(filePath);
foreach (XmlNode node in document.GetElementsByTagName("a:regionCode"))
Console.WriteLine(node.InnerText);

Use XML Literals in C#?

Is it possible to add literal XML data within a C# code file? I'm currently using a multiline string literal but it gets messy as you can see. Any better way of doing this?
string XML = #"<?xml version=""1.0"" encoding=""utf-8""?>
<customUI xmlns=""http://schemas.example.com/customui"">
<toolbar id=""save"">
</toolbar>
</customUI>";
XML literals are a feature of VB.NET, not C#.
What you have posted is as close as you can get in C#.
You may want to consider replacing the embedded double quotes with single quotes though (as both types are valid XML).
For larger amounts of XML you may want to consider the answer from Marc - using an XML file (loaded once and stored in memory), so you can take advantage of the XML editor.
If the XML is big enough to get in the way, consider using a flat .xml file instead, either loaded from disk, or embedded as a resource. As long as you only load it once (perhaps in a static constructor) this will make no difference to performance. It will be considerably easier to maintain, as it will use the IDE's XML file editor. And it won't get in the way of your code.
With reference to my comment, I couldn't recall where I saw this, but I finally found the XmlBuilder link.
In retrospect, it seems Linq to XML would be your best bet. It's cleaner, faster and more maintainable than concatenating XML strings:
XNamespace ns = "http://schemas.example.com/customui";
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement(ns + "customUI",
new XElement(ns + "taskbar",
new XAttribute("id", "save"))
)
);
var stringWriter = new StringWriter();
doc.Save(stringWriter); //Write to StringWriter, preserving the declaration (<?xml version="1.0" encoding="utf-16" standalone="yes"?>)
var xmlString = stringWriter.ToString(); //Save as string
doc.Save(#"d:\out.xml"); //Save to file
As a peculiar, and very case-specific solution, if you happen to be working in an ASP.NET environment using the Razor engine, in a CSHTML file you can:
Func<MyType, HelperResult> xml = #<root>
<item>#(item.PropertyA)</item>
<item>#(item.PropertyB)</item>
<item>#(item.PropertyC)</item>
</root>;
With the addition of an extension method:
public static XDocument ToXDocument<T>(this Func<T, HelperResult> source, T item)
{
return XDocument.Parse(source(item).ToHtmlString());
}
You can then:
XDocument document = xml.ToXDocument(new MyType() {
PropertyA = "foo",
PropertyB = "bar",
PropertyC = "qux",
});
Again, peculiar? Yes. Case-specific? Yes. But it works, and gives great Intellisense. (mind you, it also will give a bunch of validity warnings, depending on the document validation version)
The closest we could have in C# would be through LINQ, something like that:
var xml = XDocument.Load(
new StringReader(#"<Books>
<Book author='Dan Brown'>The Da Vinci Code</Book>
<Book author='Dan Brown'>The Lost Symbol</Book>
</Books>"));
var query = from book in xml.Elements("Books").Elements("Book")
where book.Attribute("author").Value == "Dan Brown"
select book.Value;
foreach (var item in query) Console.WriteLine(item);

C# Xml Parsing from StringBuilder

I have a StringBuilder with the contents of an XML file. Inside the XML file is a root tag called <root> and contains multiple <node> tags.
I'd like to parse through the XML to read values of tags within in s, but not sure how to do it.
Will I have to use some C# XML data type for this?
Thanks in advance
StringBuilder sb = new StringBuilder (xml);
TextReader textReader = new StringReader (sb.ToString ());
XDocument xmlDocument = XDocument.Load (textReader);
var nodeValueList = from node in xmlDocument.Descendants ("node")
select node.Value;
You should use classes available in either System.Xml or System.Xml.Linq to parse XML.
XDocument is part of the LINQ extensions for XML and is particularly easy to use if you need to parse through an arbitrary structure. I would suggest using it rather than XmlDocument (unless you have legacy code or are not on .NET 3.5).
Creating an XDocument from a StringBuilder is straightforward:
var doc = XDocument.Parse( stringBuilder.ToString() );
From here, you can use FirstNode, Descendents(), and the many other properties and methods available to walk and examine the XML structure. And since XDocument is designed to work well with LINQ, you can also write queries like:
var someData = from node in doc.Descendants ("yourNodeType")
select node.Value; // etc..
If you are just looking the specifically named nodes then you don't need to load the document into memory, you can process it yourself with an XmlReader.
using(var sr = new StringReader(stringBuilder.ToString)) {
using(var xr = XmlReader.Create(sr)) {
while(xr.Read()) {
if(xr.IsStartElement() && xr.LocalName == "node")
xr.ReadElementString(); //Do something here
}
}
}
use XDocument.Parse(...)
There are several objects at your disposal for working with XML. Look at the System.Xml namespace for objects such as XmlDocument as well as the XmlReader and XmlWriter families of objects. If using C# 3.0+, look at the System.Xml.Linq namespace and the XDocument class.
If you're looking to read all the values in the XML file , you could look into deserializing the XML into a C# data Object.
Deserializing XML into class obj in C#
Yes, I suggest you use an XmlDocument object to parse the content of your string.
Here is an example who print all inner text contained in your tags:
var doc=new XmlDocument();
doc.LoadXml(stringBuilder.TosTring());
XmlNodeList elemList = doc.GetElementsByTagName("node");
for (int i=0; i < elemList.Count; i++)
{
XmlNode node=elemList[i];
Console.WriteLine(node.InnerText);
}
using Node object members, you can also easily extract all you attributes .

Categories

Resources