XDocument namespace c#

388 views Asked by At

i write some application on MVC and i need to make that stuff which i write i need to get xml response like this:

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

i create this code, it easy to look which create XDocument with Xelements from database and for the first Xelement i had addin namespace but its wants to work propertly, what is my problem?:

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

and i get that why i get so "xmlns" near shepherd?:

<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

There are 1 answers

2
Martin Honnen On BEST ANSWER

You need to create all elements in the namespace, as with

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