OmniOwl
OmniOwl

Reputation: 5709

XML formatting comes out wrong

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

Upvotes: 1

Views: 155

Answers (2)

SuncoastOwner
SuncoastOwner

Reputation: 263

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

Upvotes: 2

Codor
Codor

Reputation: 17605

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

Upvotes: 1

Related Questions