XML formatting comes out wrong - c#

I am trying to make an XML document through C# with a specific format, but I am having trouble getting it to look right. Here is what it comes out as:
<?xml version="1.0" encoding="UTF-8" ?>
<loanRequest d1p1:ssn=""
d1p2:creditScore=""
d1p3:loanAmount=""
d1p4:loanDuration=""
xmlns:d1p4="26-08-2015 12:41:11"
xmlns:d1p3="147862"
xmlns:d1p2="266"
xmlns:d1p1="765383-2478" />
Here is what it should have been:
<?xml version="1.0" encoding="UTF-8" ?>
<LoanRequest>
<ssn>765383-2478</ssn>
<creditScore>266</creditScore>
<loanAmount>147862</loanAmount>
<loanDuration>2015-08-26 12:41:11.0 CET</loanDuration>
</LoanRequest>
XML manipulation in C# is really confusing to me and I have a hard time piecing together how to do it. The code that I use to make the XML document is as follows:
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode loanRequest = doc.CreateElement("loanRequest");
XmlAttribute ssn = doc.CreateAttribute("ssn", l.SSN);
XmlAttribute creditscore = doc.CreateAttribute("creditScore", ""+l.CreditScore);
XmlAttribute loanamount = doc.CreateAttribute("loanAmount", ""+l.LoanAmount);
XmlAttribute loanduration = doc.CreateAttribute("loanDuration", l.LoanDuration.ToString());
loanRequest.Attributes.Append(ssn);
loanRequest.Attributes.Append(creditscore);
loanRequest.Attributes.Append(loanamount);
loanRequest.Attributes.Append(loanduration);
doc.AppendChild(loanRequest);

Why not use Linq to Xml
XDocument doc = new XDocument(
new XComment("this is a comment"),
new XElement("LoanRequest",
new XElement("ssn", l.SSN),
new XElement("creditScore", l.CreditScore),
new XElement("loanAmount", l.LoanAmount),
new XElement("loanDuration", l.loanDuration.ToString())));
doc.Save(path);

Apparently you add as attributes what should be nodes. Replace the calls of CreateAttribute with calls of AppendChild.

Related

Document.SelectNodes returning zero nodes. Is there anything wrong in my xml?

I have following xml. But, when I am loading it and selecting node I am getting 0 nodes. Is there anything wrong with my xml?
Code to load xml :
XmlDocument doc = new XmlDocument();
doc.LoadXml(strOfferListing);
XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("ns", "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd");
mgr.AddNamespace("root", "http://mws.amazonservices.com/schema/Products/2011-10-01");
var nodes = doc.SelectNodes("//GetMatchingProductResponse");
This is my xml file :
<?xml version="1.0" encoding="UTF-8"?>
<GetMatchingProductResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01"><GetMatchingProductResult ASIN="0470265957" status="Success"><Product><Identifiers><MarketplaceASIN><MarketplaceId>XXXXXXXXXX</MarketplaceId><ASIN>0470265957</ASIN></MarketplaceASIN></Identifiers><AttributeSets><ns2:ItemAttributes xml:lang="en-US" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd"><ns2:Author>Milton H. Erickson</ns2:Author><ns2:Author>Ernest L. Rossi</ns2:Author><ns2:Binding>Hardcover</ns2:Binding><ns2:Edition>1st</ns2:Edition><ns2:IsEligibleForTradeIn>true</ns2:IsEligibleForTradeIn><ns2:Label>Irvington Publishers</ns2:Label><ns2:Languages><ns2:Language><ns2:Name>english</ns2:Name><ns2:Type>Published</ns2:Type></ns2:Language><ns2:Language><ns2:Name>english</ns2:Name><ns2:Type>Original Language</ns2:Type></ns2:Language><ns2:Language><ns2:Name>english</ns2:Name><ns2:Type>Unknown</ns2:Type></ns2:Language></ns2:Languages><ns2:ListPrice><ns2:Amount>211.86</ns2:Amount><ns2:CurrencyCode>USD</ns2:CurrencyCode></ns2:ListPrice><ns2:Manufacturer>Irvington Publishers</ns2:Manufacturer><ns2:NumberOfItems>1</ns2:NumberOfItems><ns2:NumberOfPages>512</ns2:NumberOfPages><ns2:PackageDimensions><ns2:Height Units="inches">1.70</ns2:Height><ns2:Length Units="inches">9.40</ns2:Length><ns2:Width Units="inches">6.30</ns2:Width><ns2:Weight Units="pounds">1.85</ns2:Weight></ns2:PackageDimensions><ns2:ProductGroup>Book</ns2:ProductGroup><ns2:ProductTypeName>ABIS_BOOK</ns2:ProductTypeName><ns2:PublicationDate>1979-10-01</ns2:PublicationDate><ns2:Publisher>Irvington Publishers</ns2:Publisher><ns2:SmallImage><ns2:URL>http://ecx.images-amazon.com/images/I/51geup2R-DL._SL75_.jpg</ns2:URL><ns2:Height Units="pixels">75</ns2:Height><ns2:Width Units="pixels">56</ns2:Width></ns2:SmallImage><ns2:Studio>Irvington Publishers</ns2:Studio><ns2:Title>Hypnotherapy: An Exploratory Casebook</ns2:Title></ns2:ItemAttributes></AttributeSets><Relationships /><SalesRankings><SalesRank><ProductCategoryId>book_display_on_website</ProductCategoryId><Rank>562887</Rank></SalesRank><SalesRank><ProductCategoryId>3558816011</ProductCategoryId><Rank>63</Rank></SalesRank><SalesRank><ProductCategoryId>173514</ProductCategoryId><Rank>38091</Rank></SalesRank></SalesRankings></Product></GetMatchingProductResult></GetMatchingProductResponse>

How to add attribute value in xml

i use this code for creating xml file using c# class.
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode RootNode = doc.CreateElement("SDF");
doc.AppendChild(RootNode);
XmlAttribute rootAttribute2 = doc.CreateAttribute("Version");
rootAttribute2.Value = "3.0";
RootNode.Attributes.Append(rootAttribute2);
XmlAttribute rootAttribute = doc.CreateAttribute("xmlns:sdf");
rootAttribute.Value = "http://www.w3.org/2001/XMLSchema-instance";
RootNode.Attributes.Append(rootAttribute);
XmlAttribute rootAttribute1 = doc.CreateAttribute("sdf:noNamespaceSchemaLocation");
rootAttribute1.Value = "SDF.xsd";
RootNode.Attributes.Append(rootAttribute1);
output of this code..
<?xml version="1.0" encoding="UTF-8"?>
<SDF Version="3.0" xmlns:sdf="http://www.w3.org/2001/XMLSchema-instance" noNamespaceSchemaLocation="SDF.xsd">
but i want output like that
<?xml version="1.0" encoding="UTF-8"?>
<SDF Version="3.0" xmlns:sdf="http://www.w3.org/2001/XMLSchema-instance" sdf:noNamespaceSchemaLocation="SDF.xsd">
You need to use a different overload:
XmlAttribute rootAttribute1 =
doc.CreateAttribute("sdf", "noNamespaceSchemaLocation", null);
Use Overloaded version CreateAttribute method.
doc.CreateAttribute("name","namespaceURI")
See below link for detials.
http://msdn.microsoft.com/en-us/library/System.Xml.XmlDocument.CreateAttribute%28v=vs.110%29.aspx
i searched on google and find answer that solve my problem
XmlNode RootNode = doc.CreateElement("SDF");
doc.AppendChild(RootNode);
XmlAttribute rootAttribute2 = doc.CreateAttribute("Version");
rootAttribute2.Value = "3.0";
RootNode.Attributes.Append(rootAttribute2);
XmlAttribute newAttr = doc.CreateAttribute("sdf", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
newAttr.Value = "SDF.xsd";
RootNode.Attributes.Append(newAttr);

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>

How to print <?xml version="1.0"?> using XDocument

Is there any way to have an XDocument print the xml version when using the ToString method? Have it output something like this:
<?xml version="1.0"?>
<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...
I have the following:
var xdoc = new XDocument(new XDocumentType("Response", null, null, "\n"), ...
which will print this which is fine, but it is missing the "<?xml version" as stated above.
<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...
I know that you can do this by outputting it manually my self. Just wanted to know if it was possible by using XDocument.
By using XDeclaration. This will add the declaration.
But with ToString() you will not get the desired output.
You need to use XDocument.Save() with one of his methods.
Full sample:
var doc = new XDocument(
new XDeclaration("1.0", "utf-16", "yes"),
new XElement("blah", "blih"));
var wr = new StringWriter();
doc.Save(wr);
Console.Write(wr.ToString());
This is by far the best way and most managable:
var xdoc = new XDocument(new XElement("Root", new XElement("Child", "台北 Táiběi.")));
string mystring;
using(var sw = new MemoryStream())
{
using(var strw = new StreamWriter(sw, System.Text.UTF8Encoding.UTF8))
{
xdoc.Save(strw);
mystring = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray());
}
}
and i say that just because you can change encoding to anything by changing .UTF8 to .Unicode or .UTF32
Late answer to an old question, but I shall try to provide more details than the other answers.
The thing you ask about, is called an XML declaration.
First of all, the XDocument has a property Declaration of type XDeclaration for this. You can either user another overload of the XDocument constructor:
var xdoc = new XDocument(
new XDeclaration("1.0", null, null), // <--- here
new XDocumentType("Response", null, null, "\n"), ...
);
or set the property later:
xdoc.Declaration = new XDeclaration("1.0", null, null);
But depending on how you save or write your XDocument later, the declaration (or parts of it) may be ignored. More on that later.
The XML declaration can have a number of appearances. Here are some valid examples:
<?xml version="1.0"?> new XDeclaration("1.0", null, null)
<?xml version="1.1"?> new XDeclaration("1.1", null, null)
<?xml version="1.0" encoding="us-ascii"?> new XDeclaration("1.0", "us-ascii", null)
<?xml version="1.0" encoding="utf-8"?> new XDeclaration("1.0", "utf-8", null)
<?xml version="1.0" encoding="utf-16"?> new XDeclaration("1.0", "utf-16", null)
<?xml version="1.0" encoding="utf-8" standalone="no"?> new XDeclaration("1.0", "utf-8", "no")
<?xml version="1.0" encoding="utf-8" standalone="yes"?> new XDeclaration("1.0", "utf-8", "yes")
<?xml version="1.0" standalone="yes"?> new XDeclaration("1.0", null, "yes")
Note that XDeclaration will happily accept invalid arguments, so it is up to you to get it right.
In many cases the first one, <?xml version="1.0"?>, the form you ask for, is perfect (it is not needed to give encoding if it is just UTF-8 (including ASCII), and it is not needed to specify standalone if its intended value is "no" or if there are no DTDs).
Note that xdoc.ToString() goes do the override from the XNode base class (in my version of .NET) and does not include the XML declaration. You can easily enough create a method to deal with that, like this:
public static string ToStringWithDecl(this XDocument d)
=> $"{d.Declaration}{Environment.NewLine}{d}";
Some of the other answers indicate that the XDeclaration will be respected if you use xdoc.Save or xdoc.WriteTo methods, but that is not quite true:
They might include an XML declaration even if you have none in your XDocument
They might specify the encoding used by the target file, stream, writer, string builder etc. instead of the encoding you gave, or instead of omitting the encoding if you did that in your XDeclaration
They might change your version from e.g. 1.1 into 1.0
Of course, when you save/write to a file, it is a good thing that the declaration matches the true encoding of that file!
But sometimes when you write to a string in mememory, you do not want the utf-16 (even if you realize that .NET strings are in UTF-16 internally). You can use the extension method above instead. Or you can use the following hacked version of the method from EricSch's answer:
string xdocString;
using (var hackedWriter = new SuppressEncodingStringWriter())
{
xdoc.Save(hackedWriter);
xdocString = hackedWriter.ToString();
}
where you have:
// a string writer which claims its encoding is null in order to omit encoding in XML declarations
class SuppressEncodingStringWriter : StringWriter
{
public sealed override Encoding Encoding => null;
}
Addition. Whoever updated the type StringWriter (and its base type TextWriter) to use nuallable reference types, decided that properties such as Encoding and FormatProvider should not be nullable. Maybe that was unfortunate? Anyway, if you have nullable reference types turned on, you may need to write null! instead of just null.
Just type this
var doc =
new XDocument (
new XDeclaration ("1.0", "utf-16", "no"),
new XElement ("blah", "blih")
);
And you get
<?xml version="1.0" encoding="utf-16" standalone="no"?>
<blah>blih</blah>
VB.NET Solution CODE
Code
Dim _root As XElement = <root></root>
Dim _element1 As XElement = <element1>i am element one</element1>
Dim _element2 As XElement = <element2>i am element one</element2>
_root.Add(_element1)
_root.Add(_element2)
Dim _document As New XDocument(New XDeclaration("1.0", "UTF-8", "yes"), _root)
_document.Save("c:\xmlfolder\root.xml")
Output Note(please open output in notepad )
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<element1>i am element one</element1>
<element2>i am element one</element2>
</root>
The easier way is:
var fullXml = $"{xDocument.Declaration}{xDocument}";
If your xDocument.Declaration is empty, just add it.

Categories