无法使用XDocument正确填充数据

时间:2013-05-29 07:07:45

标签: c# linq-to-xml

我有一个XML文件

<Rules>
  <Rule ruleMasterId ="7" id="SN007" name="ViewNamingFormat" forTable="False" forSP="False" forView="true" forFn="false" forScript="False" action="1" enabled="True" >
    <Description>Follow view naming format</Description>
    <ErrorMessage>View name should start with vw </ErrorMessage>
    <regex><![CDATA[^(vw|VW)?=.*[A-Za-z0-9]*$]]></regex>
  </Rule>
  <Rule ruleMasterId ="8" id="SN008" name="InvalidSchemaIdentifiers" forTable="true" forSP="true" forView="true" forFn="true" forScript="false" action="1" enabled="True" >
    <Description>Maintain schema type while addressing object name. </Description>
    <ErrorMessage>Missing schema while addressing object name</ErrorMessage>
    <DefaultValues>dbo,test</DefaultValues>
  </Rule>
</Rules>

我正在尝试使用以下代码填充值

string filePath = @"D:\RuleMaster.xml";
                //Load xml
                XDocument xdoc = XDocument.Load(filePath);


                var xx = (from rule in xdoc.Descendants("Rule")
                 select new
                 {
                     ID = rule.Attribute("id").Value,
                     Name = rule.Attribute("name").Value,
                     ForTable = Convert.ToBoolean(rule.Attribute("forTable").Value),
                     IsForSP = Convert.ToBoolean(rule.Attribute("forSP").Value),
                     IsForUDF = Convert.ToBoolean(rule.Attribute("forFn").Value),
                     IsForView = Convert.ToBoolean(rule.Attribute("forView").Value),
                     IsForScript = Convert.ToBoolean(rule.Attribute("forScript").Value),
                     Enabled = Convert.ToBoolean(rule.Attribute("enabled").Value),
                     Description = rule.Element("Description").Value,
                     ErrorMessage = rule.Element("ErrorMessage").Value,
                     Regex = rule.Attribute("regex") == null ? string.Empty : rule.Attribute("regex").Value,
                     DefaultValues = rule.Attribute("DefaultValues") == null ? string.Empty : rule.Attribute("DefaultValues").Value
                 }
                ).ToList();

但是“默认值”,“正则表达式”一片空白。为什么?知道我错在哪里吗?

2 个答案:

答案 0 :(得分:3)

DefaultValuesregex 元素不是属性

答案 1 :(得分:0)

Regex = rule.Element("regex") == null ? string.Empty : rule.Element("regex").Value,
DefaultValues = rule.Element("DefaultValues") == null ? string.Empty : rule.Element("DefaultValues").Value