How to display xml elements from within a Razor vi

2019-07-02 15:11发布

问题:

How to hardcode and display xml elements from within a Razor view.

I'd like to display the below elements for example as they are within a element:

<profile>
    <status>Active</status> 
    <userIdentifier>24d05ce9-7d11-4f06-a9eb-9f33ceac7f91</userIdentifier> 
    <firstName>dd</firstName>
    <lastName>dasd</lastName>
    <title>Ms</title>
    <emailAddress>test@test.co.uk</emailAddress>
    <companyAddress>
        <companyName></companyName>
        <addressLine1></addressLine1>
        <addressLine2></addressLine2>
        <addressLine3>Sutton</addressLine3>
        <addressLine4>Surrey</addressLine4>
        <town>Sutton</town>
        <stateOrCounty>Surrey</stateOrCounty>
        <postOrZipCode>SM1 5AS</postOrZipCode>
        <country>United Kingdom</country>
        <region/>
    </companyAddress>
    <contactAddress>        
        <addressLine1>30 Park Avenue South</addressLine1>
        <addressLine2>New York </addressLine2>
        <addressLine3>NY 11010</addressLine3>
        <addressLine4>USA</addressLine4>
        <town>NY</town>
        <stateOrCounty>NY</stateOrCounty>
        <postOrZipCode>11010</postOrZipCode>
        <country>United States</country>
        <region></region>
    </contactAddress>
    <demographics>
        <demographic key="ESOATDropDownList1">
            <answer>True</answer>
        </demographic>
    </demographics>
</profile>

How could it be done?

I know it can be written inside a control. Is there any better/easier approach?

回答1:

You may try this:

@{
   var profileXml = @"
<profile>
    <!-- your xml -->
</profile>";
}
<pre>
    @Html.Raw(Html.Encode(profileXml))
</pre>

Here profileXml contains the XML string.



回答2:

If you have the XML in the controller you can use return xml content:

public ActionResult XmlContent()
{
    string xml = @"<profile>
                     <!-- your xml -->
                   </profile>";
    return Content(xml, "text/xml");            
}