簡體   English   中英

XDocument名稱空間C#

[英]XDocument namespace c#

我在MVC上編寫了一些應用程序,我需要制作我寫的東西,我需要獲得xml響應,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<getAllShepherdsResponse xmlns="http://www.sheeps.pl/webapi/1_0">
  <shepherds>
    <shepherd>
      <errors>
        <error code="1">error1</error>
        <error code="-2147483647">error2</error>
        <error code="2147483647">error3</error>
      </errors>
      <shepherdId>1</shepherdId>
      <name>name1</name>
      <sheeps>
        <sheep>
          <id>1</id>
          <colour>colour1</colour>
          <createdOn>1900-01-01T01:01:01+01:00</createdOn>
        </sheep>
        <sheep>
          <id>-2147483647</id>
          <colour>colour2</colour>
          <createdOn>0001-01-01T00:00:00+01:00</createdOn>
        </sheep>
      </sheeps>
    </shepherd>
  </shepherds>
</getAllShepherdsResponse>

我創建了這段代碼,很容易看出是使用數據庫中的Xelements創建了XDocument,對於第一個Xelement我有addin命名空間,但它想正確地工作,我的問題是什么?:

protected XNamespace xn = "http://www.sheeps.pl/webapi/1_0";
XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement(xn+"getAllShepherdsResponse",
from emp in db.Shepherds.ToList()
select new XElement("shepherd",
new XElement("shepherdId", emp.Id),
new XElement("name", emp.Name),
new XElement("sheeps", from sp in emp.Sheep
select new 
XElement("sheep", new XElement("id", sp.Id), new XElement("colour", sp.Colour),new XElement("createdOn", sp.CreatedOn))))));

我明白為什么我在牧羊人附近會得到“ xmlns”嗎?

<getAllShepherdsResponse xmlns="http://www.sheeps.pl/webapi/1_0">
  <shepherd xmlns="">
    <shepherdId>1</shepherdId>
    <name>A</name>
    <sheeps>
      <sheep>
        <id>1</id>
        <colour>Red</colour>
        <createdOn />
      </sheep>
      <sheep>
        <id>2</id>
        <colour>Blue</colour>
        <createdOn />
      </sheep>
    </sheeps>
  </shepherd>
</getAllShepherdsResponse>

您需要在名稱空間中創建所有元素,就像

new XElement(xn+"getAllShepherdsResponse",
from emp in db.Shepherds.ToList()
select new XElement(xn+"shepherd",
new XElement(xn+"shepherdId", emp.Id),
new XElement(xn+"name", emp.Name),
new XElement(xn+"sheeps", from sp in emp.Sheep
select new 
XElement(xn+"sheep", new XElement(xn+"id", sp.Id), new XElement(xn+"colour", sp.Colour),new XElement(xn+"createdOn", sp.CreatedOn))))));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM