2012-02-27 60 views
-1

我需要复制使用LINQ to XML和C#以下XML头:如何使用LINQ-to-XML中的给定属性制作XML标头?

<ns0:Subject_Sample xmlns:ns0="fhrb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="fhrb file:FHRB_NEW_SUBJECT_SAMPLE.xsd" > 

第一个问题是,当我适应.NET帮助例子,事情开始从我的头消失。例如:

XElement myTree = new XElement(ns0 + "Subject_Sample", 
      new XAttribute(XNamespace.Xmlns + "ns0", "http://www.adventure-works.com")   
     ); 

给人有点什么,我需要

<ns0:Subject_Sample xmlns:ns0="http://www.adventure-works.com"> 

,但如果我从网页URL更改XAttribute参数字符串(如“fhrb”),然后因为某些原因“NS0:”消失的标签(ns0:Subject_Sample变成了Subject_Sample)。

于是,我决定尝试用下面的代码,使schemaLocation属性:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
XNamespace ns0 = "http://www.adventure-works.com"; 
XElement myTree = new XElement(ns0 + "Subject_Sample", 
new XAttribute(XNamespace.Xmlns + "ns0", "http://www.adventure-works.com"), 
      new XAttribute(xsi+"schemaLocation", "fhrb file:/fhrb.xsd")); 

,但我得到的结果如下,奇怪P1出现。

<ns0:Subject_Sample xmlns:ns0="http://www.adventure-works.com" p1:schemaLocation="fhrb file:/fhrb.xsd" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance"> 

问题是:如何通过LINQ to XML重现所需的头部格式?这些属性的出现/消失/命名背后的逻辑是什么?

回答

0

试试这个:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
XNamespace ns0 = "fhrb"; 
XElement myTree = new XElement(ns0 + "Subject_Sample", 
            new XAttribute(XNamespace.Xmlns + "xsi", xsi), 
            new XAttribute(XNamespace.Xmlns + "ns0", ns0), 
            new XAttribute(xsi + "schemaLocation", "fhrb file:FHRB_NEW_SUBJECT_SAMPLE.xsd") 
          ); 
相关问题