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