Newbi on XML。 尝试从所有DisplayName:s读取Text属性。认为我的问题在Rule元素附近。是一种解决我的问题的方法吗?提前致谢! //马格努斯
<?xml version="1.0" encoding="utf-16"?>
<AppMgmtDigest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/SystemCenterConfigurationManager/2009/AppMgmtDigest">
<DeploymentType >
<Requirements>
<Rule xmlns="http://schemas.microsoft.com/SystemsCenterConfigurationManager/2009/06/14/Rules">
<Annotation>
<DisplayName Text="Primary device Equals True"/>
</Annotation>
</Rule>
<Rule xmlns="http://schemas.microsoft.com/SystemsCenterConfigurationManager/2009/06/14/Rules">
<Annotation>
<DisplayName Text="Operating system One of {All Windows 10 (64-bit)}"/>
</Annotation>
</Rule>
</Requirements>
</DeploymentType>
</AppMgmtDigest>
XmlDocument xml = new XmlDocument();
xml.LoadXml(SDMPackageXML);
XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("msbld","http://schemas.microsoft.com/SystemCenterConfigurationManager/2009/AppMgmtDigest");
ns.AddNamespace("msbldr","http://schemas.microsoft.com/SystemCenterConfigurationManager/2009/06/14/Rules");
XmlNodeList nodlist = xml.SelectNode("/msbld:AppMgmtDigest/msbld:DeploymentType/msbld:Requirements/msbldr:Rule", ns/@Text);
答案 0 :(得分:0)
试试xml linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
reader.ReadLine(); //skip the identification line with utf-16
XElement doc = XElement.Load(reader);
List<string> text = doc.Descendants().Where(x => x.Name.LocalName == "DisplayName").Select(x => (string)x.Attribute("Text")).ToList();
}
}
}
答案 1 :(得分:0)
首先,名称空间中有一个拼写错误:xml中的Systems
,C#中的System
。
其次,您的代码无法编译。在发布之前,请更正明显的错误。
请试试这个:
// Correct typo
ns.AddNamespace("msbldr",
"http://schemas.microsoft.com/SystemsCenterConfigurationManager/2009/06/14/Rules");
XmlNodeList nodelst = xml.SelectNodes(
"/msbld:AppMgmtDigest/msbld:DeploymentType/msbld:Requirements/msbldr:Rule//@Text", ns);
此外,您的xpath可以指定所需属性的确切路径:
"/msbld:AppMgmtDigest/msbld:DeploymentType/msbld:Requirements/msbldr:Rule/msbldr:Annotation/msbldr:DisplayName/@Text"