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

A S*_*edo 2 c# xml asp.net-mvc

我正在尝试创建一个XML文件以符合Indeed.com的Job Listing 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 ...] 
Run Code Online (Sandbox Code Playgroud)

现在,我现在有一个IEnumberable的"Jobs",它的属性与上面的每个XML元素相匹配.

生成此XML文档并将其作为ASP.NET MVC中的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>";
    ...
}
Run Code Online (Sandbox Code Playgroud)

虽然我知道这种方法可行,但是我应该采用更好的方法来生成这个XML吗?

Meh*_*iri 5

您还可以使用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))
            )
        );
    }
Run Code Online (Sandbox Code Playgroud)