使用 C#/.net 3.5 从 xml 元素检索属性的最佳方法

发布于 2024-11-26 14:11:39 字数 1368 浏览 0 评论 0原文

如果我们有这样的 XML:

<Data>
    <Cars>
      <Details>
        <Dataset se-datafilter="cars" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
        <XmlData></XmlData>
      </Details>
    </Cars>
    <Jeeps>
      <Details>
        <Dataset se-datafilter="jeeps" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
        <XmlData></XmlData>
      </Details>
    </Jeeps>
</Data>

检索 sMainTagName 的 元素中存储的所有属性值的最佳方法是什么。 sMainTagName 的值可以是“Cars”或“Jeeps”。从 UI 传递。

我现在有以下代码:

var cols = doc.XPathSelectElements("/Data/" + sMainTagName + "/Details");

string sDataFilter = String.Empty;
string sFilterCondition = String.Empty;
string sSortCol = String.Empty;                        

foreach (var att in cols.Elements("Dataset").Attributes())
{                           
    switch(att.Name.ToString())
    {
        case "se-datafilter":
            sDataFilter = att.Value;
            break;
        case "dv-filtercondition":
            sFilterCondition = att.Value;
            break;
        case "dv-sortcolumn":
            sSortCol = att.Value;
            break;
    }
}

If we have a XML like:

<Data>
    <Cars>
      <Details>
        <Dataset se-datafilter="cars" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
        <XmlData></XmlData>
      </Details>
    </Cars>
    <Jeeps>
      <Details>
        <Dataset se-datafilter="jeeps" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
        <XmlData></XmlData>
      </Details>
    </Jeeps>
</Data>

What is the best way to retrieve the values of all the attributes stored in <Dataset> element for sMainTagName. sMainTagName can either have value "Cars" or "Jeeps". Passed from the UI.

I have the following code now:

var cols = doc.XPathSelectElements("/Data/" + sMainTagName + "/Details");

string sDataFilter = String.Empty;
string sFilterCondition = String.Empty;
string sSortCol = String.Empty;                        

foreach (var att in cols.Elements("Dataset").Attributes())
{                           
    switch(att.Name.ToString())
    {
        case "se-datafilter":
            sDataFilter = att.Value;
            break;
        case "dv-filtercondition":
            sFilterCondition = att.Value;
            break;
        case "dv-sortcolumn":
            sSortCol = att.Value;
            break;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

优雅的叶子 2024-12-03 14:11:39

我是 Linq to Xml 的粉丝。这是一个例子:

static void Main(string[] args)
    {
        var rawXml =
            @"<Data>
    <Cars>
      <Details>
        <Dataset se-datafilter=""cars"" dv-datamanipulationrequired=""false"" dv-filtercondition="""" dv-sortcolumn="""" dv-gettopNrows="""" />
        <XmlData></XmlData>
      </Details>
    </Cars>
    <Jeeps>
      <Details>
        <Dataset se-datafilter=""jeeps"" dv-datamanipulationrequired=""false"" dv-filtercondition="""" dv-sortcolumn="""" dv-gettopNrows="""" />
        <XmlData></XmlData>
      </Details>
    </Jeeps>
</Data>
";

        var xDoc = XDocument.Parse(rawXml);

        var filterName = "jeeps";
        var attrs = xDoc.Descendants("Dataset").Where(
            x => string.Equals(x.Attribute("se-datafilter").Value,
                 filterName,
                 StringComparison.CurrentCultureIgnoreCase
        ))
        .Attributes();

        foreach (var attr in attrs)
        {
            Console.WriteLine(attr.Value);
        }
    }
}

I'm a fan of Linq to Xml. Here's an example:

static void Main(string[] args)
    {
        var rawXml =
            @"<Data>
    <Cars>
      <Details>
        <Dataset se-datafilter=""cars"" dv-datamanipulationrequired=""false"" dv-filtercondition="""" dv-sortcolumn="""" dv-gettopNrows="""" />
        <XmlData></XmlData>
      </Details>
    </Cars>
    <Jeeps>
      <Details>
        <Dataset se-datafilter=""jeeps"" dv-datamanipulationrequired=""false"" dv-filtercondition="""" dv-sortcolumn="""" dv-gettopNrows="""" />
        <XmlData></XmlData>
      </Details>
    </Jeeps>
</Data>
";

        var xDoc = XDocument.Parse(rawXml);

        var filterName = "jeeps";
        var attrs = xDoc.Descendants("Dataset").Where(
            x => string.Equals(x.Attribute("se-datafilter").Value,
                 filterName,
                 StringComparison.CurrentCultureIgnoreCase
        ))
        .Attributes();

        foreach (var attr in attrs)
        {
            Console.WriteLine(attr.Value);
        }
    }
}
听你说爱我 2024-12-03 14:11:39

返回一个从属性构建的字典怎么样?

return xdoc.XPathSelectElements("/Data/" + sMainTagName + "/Details/Dataset")
        .Attributes()
        .ToDictionary(attr => attr.Name, attr => attr.Value);

How about returning a dictionary, build up from the attributes.

return xdoc.XPathSelectElements("/Data/" + sMainTagName + "/Details/Dataset")
        .Attributes()
        .ToDictionary(attr => attr.Name, attr => attr.Value);
肥爪爪 2024-12-03 14:11:39

就我个人而言,我不会一开始就使用 XPath。我会做这样的事情:(

// Note - if an element in this chain doesn't exist, you'll get a
// NullReferenceException
var details = doc.Element("Data")
                 .Element(mainTagName)
                 .Element("Details")
                 .Element("Dataset");

string dataFilter = ((string) details.Attribute("se-datafilter")) ?? "";
string filterCondition= ((string) details.Attribute("dv-filtercondition")) ?? "";
string sortCol = ((string) details.Attribute("dv-sortcolumn")) ?? "";

顺便说一句,我假设只有一个数据集元素。);

这利用了这样一个事实:如果属性不存在(即您在 null 引用上调用它),则从 XAttribute 进行的显式字符串转换将返回 null。

Personally I wouldn't use XPath to start with. I'd do something like this:

// Note - if an element in this chain doesn't exist, you'll get a
// NullReferenceException
var details = doc.Element("Data")
                 .Element(mainTagName)
                 .Element("Details")
                 .Element("Dataset");

string dataFilter = ((string) details.Attribute("se-datafilter")) ?? "";
string filterCondition= ((string) details.Attribute("dv-filtercondition")) ?? "";
string sortCol = ((string) details.Attribute("dv-sortcolumn")) ?? "";

(I'm assuming there's only one Dataset element, by the way.);

This uses the fact that the explicit string conversion from XAttribute will return null if the attribute doesn't exist (i.e. you're calling it on a null reference).

如梦 2024-12-03 14:11:39

使用以下 XPath://Dataset/@*,例如:

var doc = XDocument.Load("a.txt");

var sMainTagName = "Cars";

string xPath = "Data/" + sMainTagName + "/Details/Dataset/@*";

var attr = (doc.Document.XPathEvaluate(xPath) as IEnumerable).Cast<XAttribute>();

foreach (var item in attr)
{
    Console.WriteLine("{0}: {1}", item.Name, item.Value);
}

Use following XPath: //Dataset/@*, e.g.:

var doc = XDocument.Load("a.txt");

var sMainTagName = "Cars";

string xPath = "Data/" + sMainTagName + "/Details/Dataset/@*";

var attr = (doc.Document.XPathEvaluate(xPath) as IEnumerable).Cast<XAttribute>();

foreach (var item in attr)
{
    Console.WriteLine("{0}: {1}", item.Name, item.Value);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文