在C#中生成XML时,将其生成为字符串是否存在问题?在过去,我发现以编程方式生成XML非常冗长和复杂.通过字符串连接/字符串构建器创建xml似乎更容易,但感觉就像是不好的做法.
我应该将XML生成为字符串吗?
Rob*_*Day 13
XDocument,XElement和XAttribute类使得在C#中生成xml更容易.比使用XmlDocument或XmlWriter.
作为一个例子,产生这个:
<RootElement>
<ChildElement Attribute1="Hello" Attribute2="World" />
<ChildElement Attribute1="Foo" Attribute2="Bar" />
</RootElement>
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
XDocument xDocument = new XDocument(
new XElement("RootElement",
new XElement("ChildElement",
new XAttribute("Attribute1", "Hello"),
new XAttribute("Attribute2", "World")
),
new XElement("ChildElement",
new XAttribute("Attribute1", "Foo"),
new XAttribute("Attribute2", "Bar")
)
)
);
Run Code Online (Sandbox Code Playgroud)
你有没有尝试过Linq到Xml?它不是很冗长:
XElement xml = new XElement("contacts",
new XElement("contact",
new XAttribute("id", "1"),
new XElement("firstName", "first"),
new XElement("lastName", "last")
),
new XElement("contact",
new XAttribute("id", "2"),
new XElement("firstName", "first2"),
new XElement("lastName", "last2")
)
);
Console.Write(xml);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4425 次 |
| 最近记录: |