gpt4 book ai didi

c# - 如何在 C#/ASP.NET MVC 中动态生成此 XML 页面?

转载 作者:数据小太阳 更新时间:2023-10-29 02:48:48 25 4
gpt4 key购买 nike

我正在尝试创建一个 XML 文件以符合 Indeed.com 的职位列表 XML。

看起来像:

<?xml version="1.0" encoding="utf-8"?> 
<source>
<publisher>Super X Job Site</publisher>
<publisherurl>http://www.superxjobsite.com</publisherurl>
<job>
<title><![CDATA[Sales Executive]]></title>
<date><![CDATA[Fri, 10 Dec 2005 22:49:39 GMT]]></date>
<referencenumber><![CDATA[unique123131]]></referencenumber>
<url><![CDATA[http://www.superxjobsite.com/job/123]]></url>
<company><![CDATA[Big ABC Corporation]]></company>
<city><![CDATA[Phoenix]]></city> <state><![CDATA[AZ]]></state>
<country><![CDATA[US]]></country> <postalcode><![CDATA[85003]]></postalcode>
<description><![CDATA[Some really long job description goes here.]]></description>
</job>
[ more jobs ...]

现在,现在我有一个 IEnumberable 的“Jobs”,它具有与上面的每个 XML 元素匹配的属性。

在 ASP.NET MVC 中生成此 XML 文档并将其作为 ActionResult 返回的最佳方法是什么?

一种方法是我可以像这样手动构造 XML 字符串:

String xmlDoc = "<?xml version="1.0" encoding="utf-8"?>"; 
xmlDoc += "<source>";
xmlDoc += "<publisher>Super X Job Site</publisher>";
xmlDoc += "<publisherurl>http://www.superxjobsite.com</publisherurl>";


foreach(Job job in Jobs)
{
xmlDoc += "<job>";
xmlDoc += "<description>" + job.Description + "</description>";
...
}

虽然我知道这种方法行得通,但是否有更好的方法来生成此 XML?

最佳答案

您也可以使用 LINQ to XML 完成相同的任务。

using System.Xml.Linq;
...
...
...

XDocument xmlDoc = new XDocument(
new XDeclaration("1.0", "utf-16", "true"),
new XElement("source",
new XElement("publisher","Super X Job Site"),
new XElement("publisherurl","http://www.superxjobsite.com")
)
);
foreach (Job job in jobs)
{
xmlDoc.Element("source").Add(
new XElement("job",
new XElement("title", new XCData(job.Title)),
new XElement("date", new XCData(job.Date.ToShortDateString())),
new XElement("referencenumber", new XCData(job.ReferenceNumber)),
new XElement("url", new XCData(job.Url)),
new XElement("company", new XCData(job.Company)),
new XElement("city", new XCData(job.City)),
new XElement("country", new XCData(job.Country)),
new XElement("description", new XCData(job.Description))
)
);
}

关于c# - 如何在 C#/ASP.NET MVC 中动态生成此 XML 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1678407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com