开发者

How can I get an XML attribute?

Given this XML, how can I retrive the HEX color?

<group>
    <span style="color:#DF0000; font-style: italic; font-weight: bold">Webmaster</span>
</group>

I need to retrieve everything inside of the style. Then I can use the String.Substring method with .IndexOf() to retrieve the color for my use.

Thank you for the help.

Incase anyone is curious this is what I ended up with:

XElement str = doc.XPathSelectElement("/ipb/profile/group");                
                string c开发者_StackOverflow中文版olor = str.Element("span").Attribute("style").Value;

                color = color.Substring(color.IndexOf('#'), 7);
                return color;


You can use LINQ-to-XML:

var elem = XElement.Parse(str);
var attr = elem.Element("span").Attribute("style").Value;

Note that if your HTML is not completely well-formed, you should consider using the HTML Agility Pack instead.


I'm not sure what the rest of your document looks like, but hopefully this points you in the right direction.

    var node = xdoc.Descendants("group").Descendants("span").FirstOrDefault();

    string style = node.Attribute("style").Value;

    string[] styleElements = style.Split(';');

    var colorElements = from x in styleElements
                       where x.StartsWith("color", StringComparison.InvariantCultureIgnoreCase)
                       select x;

    string colorElement = (string)colorElements.FirstOrDefault();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜