SAL*_*SAL 12 c# xelement schema namespaces
一个冗长的问题 - 请耐心等待!
我想以编程方式创建一个带有命名空间和模式的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>
Run Code Online (Sandbox Code Playgroud)
我正在使用相当出色的新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;
}
Run Code Online (Sandbox Code Playgroud)
这正确地给了我命名空间,因此:
<myroot xmlns="http://www.someurl.com/ns/myroot">
<sometag>somecontent</sometag>
</myroot>
Run Code Online (Sandbox Code Playgroud)
我的问题:如何添加架构xmlns:xsi和xsi:schemaLocation属性?
(顺便说一下,我不能使用简单的XAtttributes,因为我在属性名称中使用冒号":"会出错...)
或者我需要使用XDocument或其他LINQ类?
谢谢...
在本文中,您看起来像是新建了多个XNamespace,在根目录中添加了一个属性,然后使用两个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);
Run Code Online (Sandbox Code Playgroud)
这是一个论坛帖子,展示了如何进行策划.
感谢大卫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;
}
Run Code Online (Sandbox Code Playgroud)
似乎连接命名空间加上一个字符串,例如
w3nsp + "schemaLocation"给出一个叫做的属性
xsi:schemaLocation在生成的XML中,这是我需要的.
| 归档时间: |
|
| 查看次数: |
8710 次 |
| 最近记录: |