RSS

Most votes on xml questions 10

Most votes on xml questions 10. #91 Error inflating when extending a class #92 How to generate sample XML documents from their DTD or XSD? #93 String Resource new line /n not possible? #94 XPath with multiple conditions #95 java.net.MalformedURLException: no protocol #96 Android: ScrollView vs NestedScrollView #97 What is difference between XML Schema and DTD? #98 "ArrayAdapter requires the resource ID to be a TextView" XML problems #99 What is the correct XPath for choosing attributes that contain "foo"? #100 How to convert XML into array in PHP?

Read all the top votes questions and answers in a single page.

#91: Error inflating when extending a class (Score: 188)

Created: 2010-09-17 Last updated: 2016-05-21

Tags: java, android, xml, class, surfaceview

I’m trying to create a custom view GhostSurfaceCameraView that extends SurfaceView. Here’s my class definition file

GhostSurfaceCameraView.java:

public class GhostSurfaceCameraView extends SurfaceView implements SurfaceHolder.Callback {
    SurfaceHolder mHolder;
    Camera mCamera;
 
    GhostSurfaceCameraView(Context context) {
        super(context);
  
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
 
    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where to draw.
        mCamera = Camera.open();
        try {
            mCamera.setPreviewDisplay(holder);
        } catch (IOException exception) {
            mCamera.release();
            mCamera = null;
            // TODO: add more exception handling logic here
        }
    }
 
    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        // Because the CameraDevice object is not a shared resource, it's very
        // important to release it when the activity is paused.
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
    }   
 
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // Now that the size is known, set up the camera parameters and begin
        // the preview.
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewSize(w, h);
        parameters.set("orientation", "portrait");
        // parameters.setRotation(90); // API 5+
        mCamera.setParameters(parameters);
        mCamera.startPreview();
    }
}

And this is in my ghostviewscreen.xml:

<com.alpenglow.androcap.GhostSurfaceCameraView android:id="@+id/ghostview_cameraview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"/>

Now in the activity I made:

protected void onCreate(Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ghostviewscreen);
    }
}

When setContentView() gets called, an exception is thrown:

Binary XML file 09-17 22:47:01.958: ERROR/ERROR(337):
ERROR IN CODE:
android.view.InflateException: Binary
XML file line #14: Error inflating
class
com.alpenglow.androcap.GhostSurfaceCameraView

Can anyone tell me why I get this error? Thanks.

#91 Best answer 1 of Error inflating when extending a class (Score: 370)

Created: 2010-09-18

I think I figured out why this wasn’t working. I was only providing a constructor for the case of one parameter ‘context’ when I should have provided a constructor for the two parameter ‘Context, AttributeSet’ case. I also needed to give the constructor(s) public access. Here’s my fix:

public class GhostSurfaceCameraView extends SurfaceView implements SurfaceHolder.Callback {
        SurfaceHolder mHolder;
        Camera mCamera;

        public GhostSurfaceCameraView(Context context)
        {
            super(context);
            init();
        }
        public GhostSurfaceCameraView(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            init();
        }
        public GhostSurfaceCameraView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }

#91 Best answer 2 of Error inflating when extending a class(Score: 45)

Created: 2013-04-15 Last updated: 2018-02-09

@Tim - Both the constructors are not required, only the ViewClassName(Context context, AttributeSet attrs ) constructor is necessary. I found this out the painful way, after hours and hours of wasted time.

I am very new to Android development, but I am making a wild guess here, that it maybe due to the fact that since we are adding the custom View class in the XML file, we are setting several attributes to it in the XML, which needs to be processed at the time of instantiation. Someone far more knowledgeable than me will be able to shed clearer light on this matter though.

See also original question in stackoverflow

#92: How to generate sample XML documents from their DTD or XSD? (Score: 188)

Created: 2008-08-19 Last updated: 2008-09-25

Tags: xml, xsd, dtd, test-data

We are developing an application that involves a substantial amount of XML transformations. We do not have any proper input test data per se, only DTD or XSD files. We’d like to generate our test data ourselves from these files. Is there an easy/free way to do that?

Edit

There are apparently no free tools for this, and I agree that OxygenXML is one of the best tools for this.

#92 Best answer 1 of How to generate sample XML documents from their DTD or XSD? (Score: 180)

Created: 2008-09-03 Last updated: 2011-09-21

In Visual Studio 2008 SP1 and later the XML Schema Explorer can create an XML document with some basic sample data:

  1. Open your XSD document
  2. Switch to XML Schema Explorer
  3. Right click the root node and choose “Generate Sample Xml”

Screenshot of the XML Schema Explorer

#92 Best answer 2 of How to generate sample XML documents from their DTD or XSD?(Score: 127)

Created: 2009-07-17 Last updated: 2009-07-17

In recent versions of the free and open source Eclipse IDE you can generate XML documents from DTD and XSD files. Right-click on a given *.dtd or *.xsd file and select “Generate -> XML File…”. You can choose which root element to generate and whether optional attributes and elements should be generated.

Of course you can use Eclipse to create and edit your DTD and XSD schema files, too. And you don't need to install any plugins. It is included in the standard distribution.

See also original question in stackoverflow

#93: String Resource new line /n not possible? (Score: 187)

Created: 2011-03-28 Last updated: 2020-06-25

Tags: android, xml, android-layout, newline, android-resources

It doesn’t seem like it’s possible to add a new line /n to an XML resource string. Is there another way of doing this?

#93 Best answer 1 of String Resource new line /n not possible? (Score: 405)

Created: 2011-03-28 Last updated: 2020-06-25

use a blackslash not a forwardslash. \n

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Hello\nWorld!</string>
</resources>

Also, if you plan on using the string as HTML, you can use &lt;br /&gt; for a line break(<br />)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Hello&lt;br /&gt;World!</string>
</resources>

#93 Best answer 2 of String Resource new line /n not possible?(Score: 50)

Created: 2013-06-25 Last updated: 2020-06-20

I know this is pretty old question but it topped the list when I searched. So I wanted to update with another method.

In the strings.xml file you can do the \n or you can simply press enter:

<string name="Your string name" > This is your string.

   This is the second line of your string.\n\n Third line of your string.</string>

This will result in the following on your TextView:

This is your string.

This is the second line of your string.

Third line of your string.

This is because there were two returns between the beginning declaration of the string and the new line. I also added the \n to it for clarity, as either can be used. I like to use the carriage returns in the xml to be able to see a list or whatever multiline string I have. My two cents.

See also original question in stackoverflow

#94: XPath with multiple conditions (Score: 187)

Created: 2012-04-20 Last updated: 2015-07-15

Tags: xml, xslt, xpath

What XPath can I use to select any category with a name attribute specified and any child node author with the value specified.

I’ve tried different variations of the path below with no success:

//quotes/category[@name='Sport' and author="James Small"]

The XML:

<?xml version="1.0" encoding="utf-8"?>
<quotes>
  <category name="Sport">
   <author>James Small<quote date="09/02/1985">Quote One</quote><quote             date="11/02/1925">Quote nine</quote></author>
  </category>
   <category name="Music">
   <author>Stephen Swann
 <quote date="04/08/1972">Quote eleven</quote></author>
  </category>
  </quotes>

#94 Best answer 1 of XPath with multiple conditions (Score: 280)

Created: 2012-04-20

Try:
//category[@name='Sport' and ./author/text()='James Small']

#94 Best answer 2 of XPath with multiple conditions(Score: 37)

Created: 2012-04-20 Last updated: 2012-04-20

Use:

/category[@name='Sport' and author/text()[1]='James Small']

or use:

/category[@name='Sport' and author[starts-with(.,'James Small')]]

It is a good rule to try to avoid using the // pseudo-operator whenever possible, because its evaluation can typically be very slow.

Also:

./somename

is equivalent to:

somename

so it is recommended to use the latter.

See also original question in stackoverflow

#95: java.net.MalformedURLException: no protocol (Score: 186)

Created: 2009-11-10 Last updated: 2011-11-20

Tags: java, xml, exception

I am getting Java exception like:

java.net.MalformedURLException: no protocol

My program is trying to parse an XML string by using:

Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(xml);

The XML string contains:

String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
    "	<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
    "		<s:Header>"+
    "			<ActivityId CorrelationId=\"15424263-3c01-4709-bec3-740d1ab15a38\" xmlns=\"http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\">50d69ff9-8cf3-4c20-afe5-63a9047348ad</ActivityId>"+
    "			<clalLog_CorrelationId xmlns=\"http://clalbit.co.il/clallog\">eb791540-ad6d-48a3-914d-d74f57d88179</clalLog_CorrelationId>"+
    "		</s:Header>"+
    "		<s:Body>"+
    "			<ValidatePwdAndIPResponse xmlns=\"http://tempuri.org/\">"+
    "			<ValidatePwdAndIPResult xmlns:a=\"http://schemas.datacontract.org/2004/07/ClalBit.ClalnetMediator.Contracts\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"+
    "			<a:ErrorMessage>Valid User</a:ErrorMessage>"+
    "			<a:FullErrorMessage i:nil=\"true\" />"+
    "			<a:IsSuccess>true</a:IsSuccess>"+
    "			<a:SecurityToken>999993_310661843</a:SecurityToken>"+
    "			</ValidatePwdAndIPResult>"+
    "			</ValidatePwdAndIPResponse>"+
    "		</s:Body>\n"+
    "	</s:Envelope>\n";

Any suggestions about what is causing this error?

#95 Best answer 1 of java.net.MalformedURLException: no protocol (Score: 390)

Created: 2009-11-10 Last updated: 2018-06-29

The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

The method DocumentBuilder.parse(String) takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream or Reader, for example a StringReader. … Welcome to the Java standard levels of indirections !

Basically :

DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));

Note that if you read your XML from a file, you can directly give the File object to DocumentBuilder.parse() .

As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !

#95 Best answer 2 of java.net.MalformedURLException: no protocol(Score: 27)

Created: 2016-06-27 Last updated: 2016-06-27

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

See also original question in stackoverflow

#96: Android: ScrollView vs NestedScrollView (Score: 186)

Created: 2016-01-13 Last updated: 2019-03-22

Tags: android, xml, android-layout, android-scrollview, android-nestedscrollview

What is the difference between ScrollView and NestedScrollView? Both of them, extend FrameLayout. I want to know in depth pros and cons of both of them.

#96 Best answer 1 of Android: ScrollView vs NestedScrollView (Score: 243)

Created: 2016-01-13 Last updated: 2018-07-07

NestedScrollView as the name suggests is used when there is a need for a scrolling view inside another scrolling view. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll.

This is where NestedScrollView comes in.

#96 Best answer 2 of Android: ScrollView vs NestedScrollView(Score: 43)

Created: 2017-08-11

In addition to the nested scrolling NestedScrollView added one major functionality, which could even make it interesting outside of nested contexts: It has build in support for OnScrollChangeListener. Adding a OnScrollChangeListener to the original ScrollView below API 23 required subclassing ScrollView or messing around with the ViewTreeObserver of the ScrollView which often means even more work than subclassing. With NestedScrollView it can be done using the build-in setter.

See also original question in stackoverflow

#97: What is difference between XML Schema and DTD? (Score: 186)

Created: 2009-10-09 Last updated: 2016-03-31

Tags: xml, schema, dtd

I have googled this question, but I do not understand clearly what is an XML schema and DTD (document type definition), and why the XML schema is more powerful compared to DTD.

Any guidance would be highly appreciated.

#97 Best answer 1 of What is difference between XML Schema and DTD? (Score: 142)

Created: 2009-10-09 Last updated: 2009-10-10

From the Differences Between DTDs and Schema section of the Converting a DTD into a Schema article:

The critical difference between DTDs and XML Schema is that XML Schema utilize an XML-based syntax, whereas DTDs have a unique syntax held over from SGML DTDs. Although DTDs are often criticized because of this need to learn a new syntax, the syntax itself is quite terse. The opposite is true for XML Schema, which are verbose, but also make use of tags and XML so that authors of XML should find the syntax of XML Schema less intimidating.

The goal of DTDs was to retain a level of compatibility with SGML for applications that might want to convert SGML DTDs into XML DTDs. However, in keeping with one of the goals of XML, “terseness in XML markup is of minimal importance,” there is no real concern with keeping the syntax brief.

[…]

So what are some of the other differences which might be especially important when we are converting a DTD? Let’s take a look.

Typing

The most significant difference between DTDs and XML Schema is the capability to create and use datatypes in Schema in conjunction with element and attribute declarations. In fact, it’s such an important difference that one half of the XML Schema Recommendation is devoted to datatyping and XML Schema. We cover datatypes in detail in Part III of this book, “XML Schema Datatypes.”

[…]

Occurrence Constraints

Another area where DTDs and Schema differ significantly is with occurrence constraints. If you recall from our previous examples in Chapter 2, “Schema Structure” (or your own work with DTDs), there are three symbols that you can use to limit the number of occurrences of an element: *, + and ?.

[…]

Enumerations

So, let’s say we had a element, and we wanted to be able to define a size attribute for the shirt, which allowed users to choose a size: small, medium, or large. Our DTD would look like this:

<!ELEMENT item (shirt)>
<!ELEMENT shirt (#PCDATA)>
<!ATTLIST shirt
    size_value (small | medium | large)>

[…]

But what if we wanted size to be an element? We can’t do that with a DTD. DTDs do not provide for enumerations in an element’s text content. However, because of datatypes with Schema, when we declared the enumeration in the preceding example, we actually created a simpleType called size_values which we can now use with an element:

<xs:element name="size" type="size_value">

[…]

#97 Best answer 2 of What is difference between XML Schema and DTD?(Score: 93)

Created: 2012-05-15 Last updated: 2021-02-11

Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:

  • XML schemas are written in XML while DTD are derived from SGML syntax.
  • XML schemas define datatypes for elements and attributes while DTD doesn’t support datatypes.
  • XML schemas allow support for namespaces while DTD does not.
  • XML schemas define number and order of child elements, while DTD does not.
  • XML schemas can be manipulated on your own with XML DOM but it is not possible in case of DTD.
  • using XML schema user need not to learn a new language but working with DTD is difficult for a user.
  • XML schema provides secure data communication i.e sender can describe the data in a way that receiver will understand, but in case of DTD data can be misunderstood by the receiver.
  • XML schemas are extensible while DTD is not extensible.

Not all these bullet points are 100% accurate, but you get the gist.

On the other hand:

  • DTD lets you define new ENTITY values for use in your XML file.
  • DTD lets you extend it local to an individual XML file.

See also original question in stackoverflow

#98: "ArrayAdapter requires the resource ID to be a TextView" XML problems (Score: 185)

Created: 2012-02-14 Last updated: 2021-04-01

Tags: android, xml, android-arrayadapter

I am getting an error when trying to set my view to display the ListView for the file I want to display(text file). I am pretty sure it has something to do with the XML. I just want to display the information from this.file = fileop.ReadFileAsList("Installed_packages.txt");. My code:

public class Main extends Activity {
    private TextView tv;
    private FileOperations fileop;
    private String[] file;

    /** Called when the activity is first created. */    	
    @Override
    public void onCreate(Bundle savedInstanceState) {    		
        super.onCreate(savedInstanceState); 
        this.fileop = new FileOperations(); 
        this.file = fileop.ReadFileAsList("Installed_packages.txt"); 
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.TextView01);
        ListView lv = new ListView(this);
        lv.setTextFilterEnabled(true); 
        lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file)); 
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

              public void onItemClick(AdapterView<?> parent, View view, 	int position, long id) { 
                    // When clicked, show a toast with the TextView text 
                    Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show(); 
              } 
        });    		
        setContentView(lv);
    }
	
}

list_item.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:padding="10dp"   
    android:textSize="16sp"   
    android:textColor="#000">

</LinearLayout>

main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
<ScrollView
    android:id="@+id/SCROLLER_ID"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:fillViewport="true">
        <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:padding="5sp"
        android:id="@+id/TextView01"
        android:text="@string/hello"/>
    </ScrollView>
    
</LinearLayout>

#98 Best answer 1 of "ArrayAdapter requires the resource ID to be a TextView" XML problems (Score: 447)

Created: 2012-02-14 Last updated: 2012-11-19

The ArrayAdapter requires the resource ID to be a TextView XML exception means you don’t supply what the ArrayAdapter expects. When you use this constructor:

new ArrayAdapter<String>(this, R.layout.a_layout_file, this.file)

R.Layout.a_layout_file must be the id of a xml layout file containing only a TextView(the TextView can’t be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    // other attributes of the TextView
/>

If you want your list row layout to be something a little different then a simple TextView widget use this constructor:

new ArrayAdapter<String>(this, R.layout.a_layout_file, 
   R.id.the_id_of_a_textview_from_the_layout, this.file)

where you supply the id of a layout that can contain various views, but also must contain a TextView with and id(the third parameter) that you pass to your ArrayAdapter so it can know where to put the Strings in the row layout.

#98 Best answer 2 of "ArrayAdapter requires the resource ID to be a TextView" XML problems(Score: 32)

Created: 2015-01-26 Last updated: 2016-11-30

Soution is here

listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >

     <TextView
         android:id="@+id/textview"
         android:layout_width="match_parent"
         android:layout_height="match_parent" >
     </TextView>
</LinearLayout>

Java code :

 String[] countryArray = {"India", "Pakistan", "USA", "UK"};
 ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listitem,R.id.textview, countryArray);
 ListView listView = (ListView) findViewById(R.id.listview);
 listView.setAdapter(adapter);

See also original question in stackoverflow

#99: What is the correct XPath for choosing attributes that contain "foo"? (Score: 185)

Created: 2008-09-19 Last updated: 2015-09-21

Tags: xml, xpath

Given this XML, what XPath returns all elements whose prop attribute contains Foo (the first three nodes):

<bla>
 <a prop="Foo1"/>
 <a prop="Foo2"/>
 <a prop="3Foo"/>
 <a prop="Bar"/>
</bla>

#99 Best answer 1 of What is the correct XPath for choosing attributes that contain "foo"? (Score: 323)

Created: 2008-09-19 Last updated: 2019-04-25

//a[contains(@prop,'Foo')]

Works if I use this XML to get results back.

<bla>
 <a prop="Foo1">a</a>
 <a prop="Foo2">b</a>
 <a prop="3Foo">c</a>
 <a prop="Bar">a</a>
</bla>

Edit: Another thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the “a” elements in element “bla”, you should as others have mentioned also use

/bla/a[contains(@prop,'Foo')]

This will search you all “a” elements in your entire xml document, regardless of being nested in a “blah” element

//a[contains(@prop,'Foo')]  

I added this for the sake of thoroughness and in the spirit of stackoverflow. :)

#99 Best answer 2 of What is the correct XPath for choosing attributes that contain "foo"?(Score: 29)

Created: 2010-02-25

This XPath will give you all nodes that have attributes containing ‘Foo’ regardless of node name or attribute name:

//attribute::*[contains(., 'Foo')]/..

Of course, if you’re more interested in the contents of the attribute themselves, and not necessarily their parent node, just drop the /..

//attribute::*[contains(., 'Foo')]

See also original question in stackoverflow

#100: How to convert XML into array in PHP? (Score: 182)

Created: 2011-07-05 Last updated: 2021-04-01

Tags: php, xml

I want to convert below XML to PHP array. Any suggestions on how I can do this?

<aaaa Version="1.0">
   <bbb>
     <cccc>
       <dddd Id="id:pass" />
       <eeee name="hearaman" age="24" />
     </cccc>
   </bbb>
</aaaa>

#100 Best answer 1 of How to convert XML into array in PHP? (Score: 465)

Created: 2013-12-06 Last updated: 2015-07-11

easy!

$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

#100 Best answer 2 of How to convert XML into array in PHP?(Score: 135)

Created: 2011-07-05 Last updated: 2011-07-05

Another option is the SimpleXML extension (I believe it comes standard with most php installs.)

http://php.net/manual/en/book.simplexml.php

The syntax looks something like this for your example

$xml = new SimpleXMLElement($xmlString);
echo $xml->bbb->cccc->dddd['Id'];
echo $xml->bbb->cccc->eeee['name'];
// or...........
foreach ($xml->bbb->cccc as $element) {
  foreach($element as $key => $val) {
   echo "{$key}: {$val}";
  }
}

See also original question in stackoverflow


Notes:
  1. This page use API to get the relevant data from stackoverflow community.
  2. Content license on this page is CC BY-SA 3.0.
  3. score = up votes - down votes.