Ste*_*uer 7 c# xml linq-to-xml xml-namespaces
我只是想让我的XML更整洁,体积更小.我知道在C#中我可以这样做:
XNamespace ds = "http://schemas.microsoft.com/ado/2007/08/dataservices";
new XElement(ds + "MyDumbElementName", "SomethingStupid");
并得到一个XML simliar:
<root>
    <MyDumbElementName xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
        SomethingStupid
    </MyDumbElementName>
</root>
而不是像这样的东西:
<root xmlns:ds="http://schemas.microsoft.com/ado/2007/08/dataservices">
    <ds:MyDumbElementName>
        SomethingStupid
    </ds:MyDumbElementName>
</root>
显然,第二个版本更漂亮,更易于阅读和紧凑.有没有办法生成一个XDocument等效的紧凑版本,而不调用Parse("...")?
您可能决定承担风险并回答"否",在这种情况下,我认为公平的事情是等待其他人回答,如果没有人给出合适的答案,我会接受您的"否",否则如果有人确实提供了答案,我会标记"否".我希望你们看起来也很公平.
编辑:也许我应该更具体一点,并说我希望能够使用多个名称空间,而不仅仅是一个.
Chr*_*ers 10
您可以通过指定xmlns属性显式覆盖此行为:
XNamespace ns = "urn:test";
new XDocument (
    new XElement ("root",
        new XAttribute (XNamespace.Xmlns + "ds", ns),
        new XElement (ns + "foo",
            new XAttribute ("xmlns", ns),
            new XElement (ns + "bar", "content")
        ))
).Dump ();
<root xmlns:ds="urn:test">
  <foo xmlns="urn:test">
    <bar>content</bar>
  </foo>
</root> 
默认情况下,行为是在线指定xmlns.
XNamespace ns = "urn:test";
new XDocument (
    new XElement ("root",
        new XElement (ns + "foo",
            new XElement (ns + "bar", "content")
        ))
).Dump ();
给出输出:
<root>
  <foo xmlns="urn:test">
    <bar>content</bar>
  </foo>
</root>
因此,默认行为是您期望的行为,除非已定义名称空间:
XNamespace ns = "urn:test";
new XDocument (
    new XElement ("root",
        new XAttribute (XNamespace.Xmlns + "ds", ns),
        new XElement (ns + "foo",
            new XElement (ns + "bar", "content")
        ))
).Dump ();
<root xmlns:ds="urn:test">
  <ds:foo>
    <ds:bar>content</ds:bar>
  </ds:foo>
</root> 
| 归档时间: | 
 | 
| 查看次数: | 2278 次 | 
| 最近记录: |