C# XML格式是错误的
我试图通过C#生成一个具有特定格式的XML文档,但在使其看起来正确时遇到了困难。结果如下:C# XML格式是错误的,c#,xml,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"
<?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" />
显然,您添加了应该是节点的属性。将
CreateAttribute
的调用替换为AppendChild
的调用,为什么不使用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);
如果需要元素,为什么要创建属性?@BenRobinson我不太懂C#XML操作。我在问题中写道:PI建议查看Linq to XML以获得更流畅的XML API,但这只会给我留下一个字符串作为名称。如何添加值?类
XmlNode
有一个value
prpoerty,如本文所述,这对我来说毫无意义<代码>变量ssn=doc.CreateElement(“ssn”)。值=l.ssn代码>???不,更像是var ssn=doc.CreateElement(“ssn”);ssn.值=l.ssn代码>我收到一个错误:附加信息:无法在节点类型“Element”上设置值。
位于ssn.value=l.ssn代码>谢谢。我照你说的做了,然后得到了一个helper函数,将它转换成一个XmlDocument,然后从中获得InnerXml
,以获得正确的格式。我现在只错过了持续时间。我只能获得完整的日期,或者完整的时间,如果我在DateTime
对象本身上调用ToString()
,我只能得到我所需要的。
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);
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);