C # SelectNodes для основного атрибута узла - PullRequest
0 голосов
/ 18 декабря 2018

Я пытаюсь получить значение атрибута logicName главного узла этого XML-файла:

<?xml version="1.0" encoding="ISO-8859-1"?>
<ticketlayout xmlns="http://www.example.com/ticketlayout" logicalName="target.xml" deviceCode="1" measurement="mm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/ticketlayout">
    <fontdefinition id="BarCode">
         <fontname>Code128bWin</fontname>
         <size measure="pt">16</size>
    </fontdefinition>
</ticketlayout>

Я попытался добавить пространство имен "xsi", "http://www.w3.org/2001/XMLSchema-instance" таким образом:

XmlDocument fLayout = new XmlDocument();
fLayout.Load("myFile.xml");
XmlNamespaceManager nsmRequestLayout = new XmlNamespaceManager(fLayout.NameTable);
nsmRequestLayout.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
string sValue = fLayout.SelectNodes("//ticketlayout", nsmRequestLayout)[0].Attributes["name"].Value;

Но я не получаю узлов. Я пробовал без пространства имен и снова без узлов и сына. On Может кто-нибудь помочь мне?

Спасибо ввперед.

Ответы [ 2 ]

0 голосов
/ 18 декабря 2018

Прежде всего, ваш XML недействителен.Я изменил, чтобы выглядеть так, чтобы достичь того, что вы ищете.XML-файл:

<?xml version="1.0" encoding="UTF-8"?>
<ticketlayout xmlns="http://www.example.com/ticketlayout" logicalName="target.xml" deviceCode="1" measurement="mm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/ticketlayout">
    <fontdefinition id="BarCode">
         <fontname>Code128bWin</fontname>
         <size measure="pt">16</size>
    </fontdefinition>
</ticketlayout>

Я не уверен, почему у вас не было бы структуры модели для десериализации вашего xml и доступа к любому нужному свойству / атрибуту.

Пример: Классы:

 [XmlRoot(ElementName = "size", Namespace = "http://www.example.com/ticketlayout")]
    public class Size
    {
        [XmlAttribute(AttributeName = "measure")]
        public string Measure { get; set; }
        [XmlText]
        public string Text { get; set; }
    }

    [XmlRoot(ElementName = "fontdefinition", Namespace = "http://www.example.com/ticketlayout")]
    public class Fontdefinition
    {
        [XmlElement(ElementName = "fontname", Namespace = "http://www.example.com/ticketlayout")]
        public string Fontname { get; set; }
        [XmlElement(ElementName = "size", Namespace = "http://www.example.com/ticketlayout")]
        public Size Size { get; set; }
        [XmlAttribute(AttributeName = "id")]
        public string Id { get; set; }
    }

    [XmlRoot(ElementName = "ticketlayout", Namespace = "http://www.example.com/ticketlayout")]
    public class Ticketlayout
    {
        [XmlElement(ElementName = "fontdefinition", Namespace = "http://www.example.com/ticketlayout")]
        public Fontdefinition Fontdefinition { get; set; }
        [XmlAttribute(AttributeName = "xmlns")]
        public string Xmlns { get; set; }
        [XmlAttribute(AttributeName = "logicalName")]
        public string LogicalName { get; set; }
        [XmlAttribute(AttributeName = "deviceCode")]
        public string DeviceCode { get; set; }
        [XmlAttribute(AttributeName = "measurement")]
        public string Measurement { get; set; }
        [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Xsi { get; set; }
        [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
        public string SchemaLocation { get; set; }
    }

Тогда вы можете использовать сериализатор:

public class Serializer
    {
        public T Deserialize<T>(string input) where T : class
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (StringReader stringReader = new StringReader(input))
            {
                return (T)xmlSerializer.Deserialize(stringReader);
            }
        }

        public string Serialize<T>(T ObjectToSerialize)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());
            StringBuilder builder = new StringBuilder();
            using (StringWriterWithEncoding textWriter = new StringWriterWithEncoding(builder, Encoding.UTF8))
            {
                xmlSerializer.Serialize(textWriter, ObjectToSerialize);
                return textWriter.ToString();
            }
        }
    }
    public class StringWriterWithEncoding : StringWriter
    {
        Encoding encoding;

        public StringWriterWithEncoding(StringBuilder builder, Encoding encoding)
        : base(builder)
        {
            this.encoding = encoding;
        }

        public override Encoding Encoding
        {
            get { return encoding; }
        }
    } 

И, наконец, вы можете получить доступ ко всему, что хотите, выполнив следующее:

var serializer = new Serializer();

//I used a local file for testing, but it should be the same thing with your file
var xmlInputData = File.ReadAllText(@"MyXmlPath");

var output = serializer.Deserialize<Ticketlayout >(xmlInputData);
var logicalName = output.LogicalName;
0 голосов
/ 18 декабря 2018

Если вы хотите получить значение: target.xml Попробуйте этот код

 XmlDocument fLayout = new XmlDocument();
        fLayout.Load("myFile.xml"); // your XML file
        var attrib = fLayout["ticketlayout"].Attributes["logicalName"].Value;
...