一个冗长的问题 - 请耐心等待我!
我想以编程方式创建一个包含名称空间和模式的XML文档。像
这样的东西<myroot
xmlns="http://www.someurl.com/ns/myroot"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.someurl.com/ns/myroot http://www.someurl.com/xml/schemas/myschema.xsd">
<sometag>somecontent</sometag>
</myroot>
我正在使用相当精彩的新LINQ内容(这对我来说是新的),并希望使用XElement来完成上述操作。
我的对象上有一个ToXElement()方法:
public XElement ToXElement()
{
XNamespace xnsp = "http://www.someurl.com/ns/myroot";
XElement xe = new XElement(
xnsp + "myroot",
new XElement(xnsp + "sometag", "somecontent")
);
return xe;
}
正确地给了我命名空间,因此:
<myroot xmlns="http://www.someurl.com/ns/myroot">
<sometag>somecontent</sometag>
</myroot>
我的问题:如何添加架构xmlns:xsi和xsi:schemaLocation属性?
(BTW我不能使用简单的XAtttributes,因为我在属性名称中使用冒号“:”会出错...)
或者我是否需要使用XDocument或其他LINQ类?
...谢谢
答案 0 :(得分:7)
从这个article看起来你新建了多个XNamespace,在root中添加一个属性,然后带着两个XNamespaces进入城镇。
// The http://www.adventure-works.com namespace is forced to be the default namespace.
XNamespace aw = "http://www.adventure-works.com";
XNamespace fc = "www.fourthcoffee.com";
XElement root = new XElement(aw + "Root",
new XAttribute("xmlns", "http://www.adventure-works.com"),
/////////// I say, check out this line.
new XAttribute(XNamespace.Xmlns + "fc", "www.fourthcoffee.com"),
///////////
new XElement(fc + "Child",
new XElement(aw + "DifferentChild", "other content")
),
new XElement(aw + "Child2", "c2 content"),
new XElement(fc + "Child3", "c3 content")
);
Console.WriteLine(root);
这是显示如何进行策划的forum post。
答案 1 :(得分:7)
感谢大卫B - 我不太确定我理解这一切,但这段代码让我得到了我需要的东西......
public XElement ToXElement()
{
const string ns = "http://www.someurl.com/ns/myroot";
const string w3 = "http://wwww.w3.org/2001/XMLSchema-instance";
const string schema_location = "http://www.someurl.com/ns/myroot http://www.someurl.com/xml/schemas/myschema.xsd";
XNamespace xnsp = ns;
XNamespace w3nsp = w3;
XElement xe = new XElement(xnsp + "myroot",
new XAttribute(XNamespace.Xmlns + "xsi", w3),
new XAttribute(w3nsp + "schemaLocation", schema_location),
new XElement(xnsp + "sometag", "somecontent")
);
return xe;
}
似乎连接命名空间加上一个字符串,例如
w3nsp + "schemaLocation",在生成的XML中给出了一个名为
xsi:schemaLocation的属性,这就是我需要的。