XML根元素解析

本文关键字:元素 XML | 更新日期: 2023-09-27 18:15:16

我正在使用以下工作良好的xml文件进行解析,但我的问题是我如何从标记<themename>获得值,因为我使用oXmlNodeList进行循环。只是不想为一个标签编写单独的例程。

XmlDocument xDoc = new XmlDocument();

List<active_theme> listActiveTheme = new List<active_theme>();
string path = AppDomain.CurrentDomain.BaseDirectory + @"themes'test'configuration.xml";
xDoc.Load(AppDomain.CurrentDomain.BaseDirectory + @"themes'test'configuration.xml");
//select a list of Nodes matching xpath expression
XmlNodeList oXmlNodeList = xDoc.SelectNodes("configuration/masterpages/masterpage");
Guid newGuid = Guid.NewGuid();
foreach (XmlNode x in oXmlNodeList)
{
    active_theme activetheme = new active_theme();
    string themepage = x.Attributes["page"].Value;
    string masterpage = x.Attributes["name"].Value;
    activetheme.active_theme_id = newGuid;
    activetheme.theme = "Dark";
    activetheme.page = themepage;
    portalContext.AddToActiveTheme(activetheme);
}
portalContext.SaveChanges();

主题配置XML文件

<configuration>
  <themename>Dark Theme</themename>
  <masterpages>
    <masterpage page="Contact" name="default.master"></masterpage>
    <masterpage page="Default" name="default.master"></masterpage>
    <masterpage page="Blue" name="blue.master"></masterpage>
    <masterpage page="red" name="red.master"></masterpage>
  </masterpages>
</configuration>

XML根元素解析

我将从LINQ to XML开始。像这样:

var doc = XDocument.Load(...);
var themeName = doc.Root.Element("themename").Value;
Guid themeGuid = Guid.NewGuid();
foreach (var element in doc.Root.Element("masterpages").Elements("masterpage"))
{
    ActiveTheme theme = new ActiveTheme
    {
        ThemeName = themeName,
        ActiveThemeId = themeGuid,
        Page = element.Attribute("page").Value,
        MasterPage = element.Attribute("name").Value
    };
    portalContent.AddToActiveTheme(theme);
}
portalContext.SaveChanges();
相关文章: