Как правильно отобразить html из файла xml на странице в Asp.Net Core 3 - PullRequest
0 голосов
/ 20 октября 2019

Я перевожу наши часто задаваемые вопросы в xml-файл в хранилище Azure, поскольку они редко меняются. Я не хочу каждый раз указывать для них значения в БД.

Моя структура выглядит следующим образом

<?xml version="1.0" encoding="utf-8" ?>
<Faqs>
  <Faq question="Welcome to our updated FAQ!" number="0" category="welcome" > 
    <Answer>       
      <p> We have updated a lot of the content on our site, including this new FAQ page. We cannot possibly think of every question you night have so please feel free to ask us to put your questions and the answers on this page.
     You can do so by clicking the link below and sending us a contact form with your question(s)
     </p>                                     
    </Answer>
    <ImageUrl value=""/>
 </Faq>
 <Faq question="What benefits does the product provide?" number="1" category="product-information" > 
   <Answer>      
    <p> A decrease in fuel consumption, substantial improvement of DPF's and an overall increase in fuel burn efficiency translate to substantial emission reductions as well. The emission benefits are achieved due to a
        <ul>
          <li>More Complete Combustion</li>
          <li>Lower Operating Temperature</li>
          <li>Lower Overall Engine Pressure</li>
       </ul>

    These factors account for the <strong>reduction of unburned</strong> carbon being released during the exhaust stroke of the engine and/or back into the oil as soot.
     </p>
    <div>
      <img alt="2strokediesel" src="~/images/2strokediesel.png" />
      <span class="image-caption">2-stroke diesel engine with the product catalytic coating area shown (orange shading)</span>
    </div>      
  </Answer>
  <ImageUrl value=""/>
</Faq>
 ...rest removed

Я думал, что для простоты поиска и создания страницы я буду хранить весь html, а не просто текст, но мой код не отображает html, поскольку он хранится в xml-файле.

Либо это невозможно сделать (редко бывает), либо есть какой-то способ кодирования / декодирования возвращаемого значения, чтобы оно отображалось правильно.

Любая помощь приветствуется.

здесьбритва для раздела страницы

 <!-- Product Information -->
        <h2 class="h3 font-w600 push-30-t push">@ti.ToTitleCase(Model.ProductInformationFaqs[0].Category)</h2>
        @for (var i = 0; i < Model.ProductInformationFaqs.Count; i++)
        {
            var identifier = $"#faq1_q{i + 1}";

            <div id="faq1" class="panel-group">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">
                            <a class="accordion-toggle" data-toggle="collapse"
                               data-parent="#faq1"
                               href="@identifier">@Model.ProductInformationFaqs[i].Question</a>
                        </h3>
                    </div>
                    @if (i == 0)
                    {
                        <div id="@identifier.Replace("#","")" class="panel-collapse collapse in">
                            <div class="panel-body">
                                @Html.Raw(Model.ProductInformationFaqs[i].Answer)
                            </div>
                        </div>
                    }
                    else
                    {
                        <div id="@identifier.Replace("#","")" class="panel-collapse collapse">
                            <div class="panel-body">
                                @Html.Raw(Model.ProductInformationFaqs[i].Answer)
                            </div>
                        </div>
                    }
                </div>
            </div>
        }
        <!-- END Product Information -->

и для полноты

Вот код извлечения файла xml, на случай, если я должен манипулировать полученным значением здесьfirst.

public List<FaqDto> GetFaqItems()
    {
        var query = _doc.Descendants("Faq")
            .Select(x => new FaqDto()
            {
                Category = x.Attribute("category")?.Value,
                Question = x.Attribute("question")?.Value,
                FaqNumber = Convert.ToInt16(x.Attribute("number")?.Value),
                Answer = x.Element("Answer")?.Value,
                ImageUrl = x.Element("ImageUrl")?.Attribute("value")?.Value
            }).ToList();

        return query;
    }
For example:

FAQ # 1 в xml должен отображать неупорядоченный список, который выглядит следующим образом

 <p>
    A decrease in fuel consumption, substantial improvement of DPF's and an overall increase in fuel burn efficiency translate to substantial emission reductions as well. The emission benefits are achieved due to a
    <ul>
       <li>More Complete Combustion</li>
       <li>Lower Operating Temperature</li>
       <li>Lower Overall Engine Pressure</li>
    </ul>

    These factors accounts for the <strong>reduction of unburned</strong> carbon being released during the exhaust stroke of the engine and/or back into the oil as soot.      

 </p>

но это выглядит так

Displaying

1 Ответ

0 голосов
/ 28 октября 2019

Если вы хотите извлечь html из элемента атрибута xml-файла, лучше всего обернуть html в элемент CDATA. Ваш xml должен выглядеть следующим образом, а затем он будет правильно извлекаться и отображаться с использованием Html.Raw (ваша строка здесь) в приложении Asp.Net Razor или MVC

Образец XML-файла

<Faqs>
  <Faq question="Welcome to our updated FAQ!" number="0" category="welcome" > 
  <Answer>  
    <![CDATA[<html>
  <p>We have updated a lot of the content on our site, including this new FAQ page. We cannot possibly think of every question you night have so please feel free to ask us to put your questions and the answers on this page. You can do so by clicking the button below and sending us a contact form with your question(s)  
  </p>
      </html>
   ]]>                                           
  </Answer>
  <ImageUrl value=""/>
  </Faq>
</Faqs>
...