XML格式错误

时间:2014-11-26 11:51:19

标签: c# xml

我正在尝试使用特定格式的C#创建XML文档,但我无法让它看起来正确。以下是它的结果:

<?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" /> 

这应该是什么:

<?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>

C#中的XML操作对我来说真的很混乱,我很难拼凑出如何做到这一点。我用来制作XML文档的代码如下:

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

2 个答案:

答案 0 :(得分:2)

为什么不将Linq用于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);

答案 1 :(得分:1)

显然你添加了应该是节点的属性。将来自CreateAttribute的来电替换为AppendChild的来电。