[英]In C#, is there a way to generate an XDocument using the short prefix instead of the full namespace for each node?
我只是想讓我的 XML 更整潔一點,體積更小。 我知道在 C# 中可以執行以下操作:
XNamespace ds = "http://schemas.microsoft.com/ado/2007/08/dataservices";
new XElement(ds + "MyDumbElementName", "SomethingStupid");
並獲得與此類似的 XML:
<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>
顯然第二個版本更漂亮、更容易閱讀、更緊湊。 有什么方法可以在不調用 Parse("...") 的情況下生成與緊湊版本等效的 XDocument?
您可能決定冒險並回答“否”,在這種情況下,我認為公平的做法是等待其他人回答,如果沒有人給出合適的答案,我將接受您的“否”,否則如果有人確實提供了答案,我會將“否”標記下來。 我希望這對你來說也是公平的。
編輯:也許我應該更具體一點,說我希望能夠使用多個名稱空間,而不僅僅是一個。
您可以通過指定 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 ();
給出 output:
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.