When styling XML with CSS, how to refer to tag nam

2019-04-10 01:22发布

问题:

I'm styling an XML document that contains tags like <a.b></a.b> or <b:c></b:c>. Now of course if I write CSS rules like

a.b {
} 

b:c {
}

It won't work because these characters will be interpreted as classes and pseudo-classes, respectively. Is there a way to refer to these tag names with CSS? (I don't want to use XSL...)

回答1:

As mentioned, to refer to an element with a . in its tag name you can simply escape it:

a\.b

But the same can't be said for a b:c element, because : has a special meaning in XML, as a namespace separator. This means that the element you have is actually a c element in the b namespace, not an element called b:c.1

That said, there are two correct ways to select that element. First, since as I mentioned the element is actually called c and not b:c, you can simply use:

c

The second way, in case of namespace collisions, is to first declare the b namespace in the beginning of your stylesheet using @namespace corresponding to the one in your XML document (there should be an xmlns:b namespace reference somewhere in your document, otherwise it won't be valid):

/* Whichever URL corresponds to xmlns:b in your XML document */
@namespace b 'http://ns.example.com/b';

Then use a namespace prefix to select the element:

b|c

1 Remember that we're talking about XML here, not HTML or any arbitrary markup language where : holds no special meaning.