XML 格式设置错误

本文关键字:错误 设置 格式 XML | 更新日期: 2023-09-27 18:31:59

我正在尝试通过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);

XML 格式设置错误

为什么不使用 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);

显然,您将应该是节点的内容添加为属性。将 CreateAttribute 的调用替换为 AppendChild 的调用。