XDocument命名空间c#

时间:2014-07-31 13:42:52

标签: c# xml asp.net-mvc linq-to-xml xnamespace

我在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))))));

我知道为什么我会这样做&#34; xmlns&#34;靠近牧羊人?:

<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>

1 个答案:

答案 0 :(得分:2)

您需要在命名空间中创建所有元素,与

一样
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))))));