读取 xml 元素值而不使用 cdata?
我有这个简单的 xml:
<AllBands>
<Band>
<Name ID="1234" started="1962">Beatles<![CDATA[lalala]]></Name>
<Last>1</Last>
<Salary>2</Salary>
</Band>
<Band>
<Name ID="222" started="1968">Doors<![CDATA[lalala]]></Name>
<Last>1</Last>
<Salary>2</Salary>
</Band>
</AllBands>
我想从 Name
元素中读取“bealtes
”值,
这是为什么
using (var stream = new StringReader(result))
{
XDocument xmlFile = XDocument.Load(stream);
var query = from c in xmlFile.Descendants("Band") select c;
foreach (XElement band in query)
{
if (band.Element("Name").Value ==...) // this expression is beatleslalala
// and not beatles alone...
}
}
?为什么他包含cdata?我怎样才能只得到“披头士乐队”?
I have this simple xml :
<AllBands>
<Band>
<Name ID="1234" started="1962">Beatles<![CDATA[lalala]]></Name>
<Last>1</Last>
<Salary>2</Salary>
</Band>
<Band>
<Name ID="222" started="1968">Doors<![CDATA[lalala]]></Name>
<Last>1</Last>
<Salary>2</Salary>
</Band>
</AllBands>
I want to read the "bealtes
" value from the Name
element
by
using (var stream = new StringReader(result))
{
XDocument xmlFile = XDocument.Load(stream);
var query = from c in xmlFile.Descendants("Band") select c;
foreach (XElement band in query)
{
if (band.Element("Name").Value ==...) // this expression is beatleslalala
// and not beatles alone...
}
}
why is that? why does he includes the cdata? How can i get the "beatles" only?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
元素节点包含两个子节点:一个文本节点和一个 CDATA 节点。元素节点的
Value
是其子节点的所有值的串联。如果你想要文本节点的值,你需要获取文本节点的
Value
,而不是元素。请注意,在读取 XML 文件时区分文本节点和 CDATA 节点是很不常见的。文件的作者应该能够使用他们喜欢的任何一个。
Your
<Name>
element node contains two child nodes: a text node and a CDATA node.The
Value
of an element node is all values of its child nodes concatenated.If you want the value of the text node, you need to get the
Value
of the text node, not the element.Note that it's quite unusual to distinguish between text nodes and CDATA nodes when reading an XML file. The author of the file should be able to use whichever they like.
您有一个文本值和一个 CDATA 节点作为 Name 的子节点,这就是原因。
如果您深入研究名称节点,您将能够找到这两个部分,但您可能需要重新设计您的 xml 结构。
事实上,它的 xsd 会很混乱。
You have a text value and a CDATA Node as children of Name is why.
If you dig about inside the name node you'll be able to find the two parts but you might want to rework your xml structure
As it is, an xsd for it is going to be messy.